diff --git a/.changeset/dry-bikes-fix.md b/.changeset/dry-bikes-fix.md deleted file mode 100644 index 7fc36535fb..0000000000 --- a/.changeset/dry-bikes-fix.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'@core/sync-service': patch ---- - -Fix typo in source event name diff --git a/.changeset/perfect-ads-reply.md b/.changeset/perfect-ads-reply.md deleted file mode 100644 index c0e2c2c934..0000000000 --- a/.changeset/perfect-ads-reply.md +++ /dev/null @@ -1,7 +0,0 @@ ---- -'@core/electric-telemetry': patch ---- - -Extend top processes by memory metric to collect processes until the specified mem usage threshold is covered. - -`ELECTRIC_TELEMETRY_TOP_PROCESS_COUNT` has been renamed to `ELECTRIC_TELEMETRY_TOP_PROCESS_LIMIT` with a new format: `count:` or `mem_percent:`. The old env var is still accepted as a fallback. diff --git a/.changeset/reclassify-branch-does-not-exist.md b/.changeset/reclassify-branch-does-not-exist.md deleted file mode 100644 index b0c97b826c..0000000000 --- a/.changeset/reclassify-branch-does-not-exist.md +++ /dev/null @@ -1,7 +0,0 @@ ---- -'@core/sync-service': patch ---- - -Reclassify `branch_does_not_exist` error as retryable. PlanetScale returns this -error transiently during cluster maintenance, and classifying it as non-retryable -caused sources to be permanently shut down requiring manual restart. diff --git a/.changeset/sour-houses-flow.md b/.changeset/sour-houses-flow.md deleted file mode 100644 index 8f391375da..0000000000 --- a/.changeset/sour-houses-flow.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'@core/electric-telemetry': patch ---- - -Group request handler processes together to see their aggregated memory usage. diff --git a/.changeset/yellow-dolls-drum.md b/.changeset/yellow-dolls-drum.md deleted file mode 100644 index 6115531b35..0000000000 --- a/.changeset/yellow-dolls-drum.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'@core/sync-service': patch ---- - -Make in-memory shape db instances isolated diff --git a/.changeset/young-bikes-switch.md b/.changeset/young-bikes-switch.md deleted file mode 100644 index 9b1125af48..0000000000 --- a/.changeset/young-bikes-switch.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'@core/sync-service': patch ---- - -Add known errors for pg authorization failures diff --git a/examples/tanstack-db-expo-starter/CHANGELOG.md b/examples/tanstack-db-expo-starter/CHANGELOG.md index 1dff233701..79af109309 100644 --- a/examples/tanstack-db-expo-starter/CHANGELOG.md +++ b/examples/tanstack-db-expo-starter/CHANGELOG.md @@ -1,5 +1,12 @@ # expo-db-electric-starter +## 1.0.15 + +### Patch Changes + +- Updated dependencies [deb7c32] + - @electric-sql/client@1.5.14 + ## 1.0.14 ### Patch Changes diff --git a/examples/tanstack-db-expo-starter/package.json b/examples/tanstack-db-expo-starter/package.json index 6e6396348c..77860e508e 100644 --- a/examples/tanstack-db-expo-starter/package.json +++ b/examples/tanstack-db-expo-starter/package.json @@ -1,6 +1,6 @@ { "name": "expo-db-electric-starter", - "version": "1.0.14", + "version": "1.0.15", "main": "index.ts", "scripts": { "start": "docker compose up -d && expo start", @@ -13,7 +13,7 @@ "api": "tsx api/index.ts" }, "dependencies": { - "@electric-sql/client": "1.5.13", + "@electric-sql/client": "1.5.14", "@expo/metro-runtime": "~5.0.4", "@tanstack/electric-db-collection": "^0.0.15", "@tanstack/react-db": "^0.0.27", diff --git a/packages/electric-telemetry/CHANGELOG.md b/packages/electric-telemetry/CHANGELOG.md index 895f13521f..6bcdefde6b 100644 --- a/packages/electric-telemetry/CHANGELOG.md +++ b/packages/electric-telemetry/CHANGELOG.md @@ -1,5 +1,15 @@ # @core/electric-telemetry +## 0.1.10 + +### Patch Changes + +- 0aa8c00: Extend top processes by memory metric to collect processes until the specified mem usage threshold is covered. + + `ELECTRIC_TELEMETRY_TOP_PROCESS_COUNT` has been renamed to `ELECTRIC_TELEMETRY_TOP_PROCESS_LIMIT` with a new format: `count:` or `mem_percent:`. The old env var is still accepted as a fallback. + +- 0aa8c00: Group request handler processes together to see their aggregated memory usage. + ## 0.1.9 ### Patch Changes diff --git a/packages/electric-telemetry/package.json b/packages/electric-telemetry/package.json index cf4cd9d983..3a434b0b44 100644 --- a/packages/electric-telemetry/package.json +++ b/packages/electric-telemetry/package.json @@ -1,5 +1,5 @@ { "name": "@core/electric-telemetry", "private": true, - "version": "0.1.9" + "version": "0.1.10" } diff --git a/packages/elixir-client/CHANGELOG.md b/packages/elixir-client/CHANGELOG.md index f2449fdb49..bdd31e5837 100644 --- a/packages/elixir-client/CHANGELOG.md +++ b/packages/elixir-client/CHANGELOG.md @@ -1,5 +1,11 @@ # @core/elixir-client +## 0.9.4 + +### Patch Changes + +- cb2c45e: Include required headers in client mock responses + ## 0.9.3 ### Patch Changes diff --git a/packages/elixir-client/lib/electric/client/mock.ex b/packages/elixir-client/lib/electric/client/mock.ex index 453fbdc183..5cbd0f9ccd 100644 --- a/packages/elixir-client/lib/electric/client/mock.ex +++ b/packages/elixir-client/lib/electric/client/mock.ex @@ -198,9 +198,11 @@ defmodule Electric.Client.Mock do end defp build_response(opts) do + opts = Keyword.put_new(opts, :next_cursor, System.unique_integer([:positive, :monotonic])) + %Fetch.Response{ status: Keyword.get(opts, :status, 200), - headers: headers(opts[:headers] || []), + headers: headers(opts), body: jsonify(opts[:body] || []), schema: Keyword.get(opts, :schema, nil), shape_handle: Keyword.get(opts, :shape_handle, nil), @@ -213,12 +215,14 @@ defmodule Electric.Client.Mock do {:shape_handle, Client.shape_handle()} | {:last_offset, Client.Offset.t()} | {:schema, Client.schema()} + | {:next_cursor, Client.cursor()} ]) :: %{String.t() => [String.t()]} def headers(args) do %{} |> put_optional_header("electric-handle", args[:shape_handle]) |> put_optional_header("electric-offset", args[:last_offset]) |> put_optional_header("electric-schema", args[:schema], &Jason.encode!/1) + |> put_optional_header("electric-cursor", args[:next_cursor]) end defp put_optional_header(headers, header, value, encoder \\ & &1) diff --git a/packages/elixir-client/package.json b/packages/elixir-client/package.json index e42b2fef2b..aa5e1d9ef3 100644 --- a/packages/elixir-client/package.json +++ b/packages/elixir-client/package.json @@ -1,7 +1,7 @@ { "name": "@core/elixir-client", "private": true, - "version": "0.9.3", + "version": "0.9.4", "scripts": { "publish:hex": "../../scripts/publish_hex.sh electric_client" } diff --git a/packages/elixir-client/test/electric/client/mock_test.exs b/packages/elixir-client/test/electric/client/mock_test.exs index ff41037813..3c5f859a82 100644 --- a/packages/elixir-client/test/electric/client/mock_test.exs +++ b/packages/elixir-client/test/electric/client/mock_test.exs @@ -20,8 +20,9 @@ defmodule Electric.Client.MockTest do start_supervised( {Task, fn -> - events = Client.stream(client, ctx.shape) |> Enum.take(5) - send(parent, {:events, events}) + client + |> Client.stream(ctx.shape) + |> Enum.each(fn evt -> send(parent, {:event, evt}) end) end} ) @@ -51,10 +52,16 @@ defmodule Electric.Client.MockTest do ] ) - events = - receive do - {:events, events} -> events - end + event_stream = + Stream.repeatedly(fn -> + receive do + {:event, event} -> event + after + 1_000 -> raise "client stream has crashed" + end + end) + + events = Enum.take(event_stream, 5) assert [ %ChangeMessage{value: %{"id" => 1111}}, @@ -63,5 +70,19 @@ defmodule Electric.Client.MockTest do %ChangeMessage{value: %{"id" => 4444}}, up_to_date(1234) ] = events + + {:ok, _request} = + Client.Mock.response(client, + status: 200, + schema: %{id: %{type: "int8"}}, + last_offset: Offset.new(0, 1), + shape_handle: "my-shape", + body: [ + Client.Mock.change(value: %{id: "5555"}), + Client.Mock.up_to_date(lsn: 1235) + ] + ) + + assert [_, up_to_date(1235)] = Enum.take(event_stream, 2) end end diff --git a/packages/experimental/CHANGELOG.md b/packages/experimental/CHANGELOG.md index eb5736ab62..6dee49d25f 100644 --- a/packages/experimental/CHANGELOG.md +++ b/packages/experimental/CHANGELOG.md @@ -1,5 +1,12 @@ # @electric-sql/experimental +## 6.0.14 + +### Patch Changes + +- Updated dependencies [deb7c32] + - @electric-sql/client@1.5.14 + ## 6.0.13 ### Patch Changes diff --git a/packages/experimental/package.json b/packages/experimental/package.json index 859b43c22a..20efc0dbdb 100644 --- a/packages/experimental/package.json +++ b/packages/experimental/package.json @@ -1,7 +1,7 @@ { "name": "@electric-sql/experimental", "description": "Experimental TypeScript features for ElectricSQL.", - "version": "6.0.13", + "version": "6.0.14", "author": "ElectricSQL team and contributors.", "bugs": { "url": "https://github.com/electric-sql/electric/issues" diff --git a/packages/react-hooks/CHANGELOG.md b/packages/react-hooks/CHANGELOG.md index 47391ab553..aa1ad840b6 100644 --- a/packages/react-hooks/CHANGELOG.md +++ b/packages/react-hooks/CHANGELOG.md @@ -1,5 +1,12 @@ # @electric-sql/react +## 1.0.43 + +### Patch Changes + +- Updated dependencies [deb7c32] + - @electric-sql/client@1.5.14 + ## 1.0.42 ### Patch Changes diff --git a/packages/react-hooks/package.json b/packages/react-hooks/package.json index 92f0d08dbb..5c403a95d8 100644 --- a/packages/react-hooks/package.json +++ b/packages/react-hooks/package.json @@ -1,7 +1,7 @@ { "name": "@electric-sql/react", "description": "React hooks for ElectricSQL", - "version": "1.0.42", + "version": "1.0.43", "author": "ElectricSQL team and contributors.", "bugs": { "url": "https://github.com/electric-sql/electric/issues" diff --git a/packages/sync-service/CHANGELOG.md b/packages/sync-service/CHANGELOG.md index 08bf7d8603..1b0915186a 100644 --- a/packages/sync-service/CHANGELOG.md +++ b/packages/sync-service/CHANGELOG.md @@ -1,5 +1,19 @@ # @core/sync-service +## 1.4.16 + +### Patch Changes + +- 6c5068a: Fix stuck flush tracker when storage flush notification arrives mid-transaction in Consumer +- 93e5d40: Fix typo in source event name +- 64a89a0: Fixed char(n) column values being trimmed of trailing spaces in snapshot and subset queries, causing inconsistency with values from PG replication. +- 8919ca3: Reclassify `branch_does_not_exist` error as retryable. PlanetScale returns this + error transiently during cluster maintenance, and classifying it as non-retryable + caused sources to be permanently shut down requiring manual restart. +- d89be52: Improve shutdown times by changing the consumer supervision strategy +- 0af96e9: Make in-memory shape db instances isolated +- 461576d: Add known errors for pg authorization failures + ## 1.4.15 ### Patch Changes diff --git a/packages/sync-service/config/runtime.exs b/packages/sync-service/config/runtime.exs index 2b4b718102..892b55cafd 100644 --- a/packages/sync-service/config/runtime.exs +++ b/packages/sync-service/config/runtime.exs @@ -207,6 +207,7 @@ config :electric, max_shapes: env!("ELECTRIC_MAX_SHAPES", :integer, nil) || env!("ELECTRIC_EXPERIMENTAL_MAX_SHAPES", :integer, nil), + consumer_partitions: env!("ELECTRIC_CONSUMER_PARTITIONS", :integer, nil), max_concurrent_requests: max_concurrent_requests, # Used in telemetry instance_id: instance_id, diff --git a/packages/sync-service/lib/electric/application.ex b/packages/sync-service/lib/electric/application.ex index c4a885e00a..2d22006f25 100644 --- a/packages/sync-service/lib/electric/application.ex +++ b/packages/sync-service/lib/electric/application.ex @@ -137,6 +137,7 @@ defmodule Electric.Application do max_shapes: get_env(opts, :max_shapes), tweaks: [ publication_alter_debounce_ms: get_env(opts, :publication_alter_debounce_ms), + consumer_partitions: get_env(opts, :consumer_partitions), registry_partitions: get_env(opts, :process_registry_partitions), publication_refresh_period: get_env(opts, :publication_refresh_period), schema_reconciler_period: get_env(opts, :schema_reconciler_period), diff --git a/packages/sync-service/lib/electric/config.ex b/packages/sync-service/lib/electric/config.ex index 5988ce3a7d..83764bb332 100644 --- a/packages/sync-service/lib/electric/config.ex +++ b/packages/sync-service/lib/electric/config.ex @@ -68,6 +68,7 @@ defmodule Electric.Config do stack_ready_timeout: 5_000, send_cache_headers?: true, max_shapes: nil, + consumer_partitions: nil, # This value should be tuned for the hardware it's running on. max_concurrent_requests: %{initial: 300, existing: 10_000}, ## Storage diff --git a/packages/sync-service/lib/electric/core_supervisor.ex b/packages/sync-service/lib/electric/core_supervisor.ex index 00b828af91..a80d88b9c0 100644 --- a/packages/sync-service/lib/electric/core_supervisor.ex +++ b/packages/sync-service/lib/electric/core_supervisor.ex @@ -44,8 +44,15 @@ defmodule Electric.CoreSupervisor do inspector = Keyword.fetch!(opts, :inspector) persistent_kv = Keyword.fetch!(opts, :persistent_kv) tweaks = Keyword.fetch!(opts, :tweaks) + max_shapes = Keyword.fetch!(opts, :max_shapes) - consumer_supervisor_spec = {Electric.Shapes.DynamicConsumerSupervisor, [stack_id: stack_id]} + consumer_supervisor_spec = + {Electric.Shapes.DynamicConsumerSupervisor, + [ + stack_id: stack_id, + max_shapes: max_shapes, + partitions: Keyword.get(tweaks, :consumer_partitions) + ]} shape_cache_spec = {Electric.ShapeCache, shape_cache_opts} @@ -69,8 +76,7 @@ defmodule Electric.CoreSupervisor do period: Keyword.get(tweaks, :schema_reconciler_period, 60_000)} expiry_manager_spec = - {Electric.ShapeCache.ExpiryManager, - max_shapes: Keyword.fetch!(opts, :max_shapes), stack_id: stack_id} + {Electric.ShapeCache.ExpiryManager, max_shapes: max_shapes, stack_id: stack_id} child_spec = Supervisor.child_spec( diff --git a/packages/sync-service/lib/electric/replication/shape_log_collector.ex b/packages/sync-service/lib/electric/replication/shape_log_collector.ex index c4597e22cf..6bbb4b6b87 100644 --- a/packages/sync-service/lib/electric/replication/shape_log_collector.ex +++ b/packages/sync-service/lib/electric/replication/shape_log_collector.ex @@ -465,17 +465,14 @@ defmodule Electric.Replication.ShapeLogCollector do OpenTelemetry.add_span_attributes("txn.is_dropped": true) - {:ok, - %{ - state - | flush_tracker: - FlushTracker.handle_txn_fragment( - state.flush_tracker, - txn_fragment, - [], - MapSet.new() - ) - }} + flush_tracker = + if txn_fragment.commit do + FlushTracker.handle_txn_fragment(state.flush_tracker, txn_fragment, []) + else + state.flush_tracker + end + + {:ok, %{state | flush_tracker: flush_tracker}} end defp handle_txn_fragment( @@ -578,22 +575,9 @@ defmodule Electric.Replication.ShapeLogCollector do flush_tracker = case event do - %TransactionFragment{} -> - shapes_with_changes = - for {id, frag} <- events_by_handle, - frag.change_count > 0, - not MapSet.member?(undeliverable_set, id), - do: id, - into: MapSet.new() - - if event.commit, do: LsnTracker.broadcast_last_seen_lsn(state.stack_id, lsn) - - FlushTracker.handle_txn_fragment( - flush_tracker, - event, - delivered_shapes, - shapes_with_changes - ) + %TransactionFragment{commit: commit} when not is_nil(commit) -> + LsnTracker.broadcast_last_seen_lsn(state.stack_id, lsn) + FlushTracker.handle_txn_fragment(flush_tracker, event, delivered_shapes) _ -> flush_tracker diff --git a/packages/sync-service/lib/electric/replication/shape_log_collector/flush_tracker.ex b/packages/sync-service/lib/electric/replication/shape_log_collector/flush_tracker.ex index 8ea1144a38..f377a3f162 100644 --- a/packages/sync-service/lib/electric/replication/shape_log_collector/flush_tracker.ex +++ b/packages/sync-service/lib/electric/replication/shape_log_collector/flush_tracker.ex @@ -95,41 +95,15 @@ defmodule Electric.Replication.ShapeLogCollector.FlushTracker do last_flushed == %{} and :gb_trees.is_empty(tree) end - @spec handle_txn_fragment( - t(), - TransactionFragment.t(), - Enumerable.t(shape_id()), - MapSet.t(shape_id()) - ) :: t() - - # Non-commit fragment: track affected shapes but don't update last_seen_offset - # or notify. This ensures shapes are registered early so flush notifications - # from Consumers aren't lost when storage flushes before the commit arrives. - def handle_txn_fragment( - %__MODULE__{} = state, - %TransactionFragment{commit: nil, last_log_offset: last_log_offset}, - affected_shapes, - _shapes_with_changes - ) do - track_shapes(state, last_log_offset, affected_shapes) - end + @spec handle_txn_fragment(t(), TransactionFragment.t(), Enumerable.t(shape_id())) :: t() - # Commit fragment: track shapes that have actual changes in this fragment - # or are already being tracked (need last_sent updated to commit offset). - # Skip shapes that only have a commit marker and already flushed from - # earlier non-commit fragments — there's nothing new to flush for them. + # Commit fragment: track all shapes affected by all fragments of the transaction and update last_seen_offset. def handle_txn_fragment( %__MODULE__{} = state, %TransactionFragment{commit: %Commit{}, last_log_offset: last_log_offset}, - affected_shapes, - shapes_with_changes + affected_shapes ) do - shapes_to_track = - Enum.filter(affected_shapes, fn shape -> - shape in shapes_with_changes or is_map_key(state.last_flushed, shape) - end) - - state = track_shapes(state, last_log_offset, shapes_to_track) + state = track_shapes(state, last_log_offset, affected_shapes) state = %{state | last_seen_offset: last_log_offset} @@ -211,14 +185,7 @@ defmodule Electric.Replication.ShapeLogCollector.FlushTracker do min_incomplete_flush_tree: min_incomplete_flush_tree } - # Only update global offset if we've seen at least one commit. - # Before any commit, last_seen_offset is before_all and there's - # nothing meaningful to report. - if state.last_seen_offset == LogOffset.before_all() do - state - else - update_global_offset(state) - end + update_global_offset(state) end # If the shape is not in the mapping, then we're processing a flush notification for a shape that was removed diff --git a/packages/sync-service/lib/electric/shapes/consumer.ex b/packages/sync-service/lib/electric/shapes/consumer.ex index abe734a678..2917bd57c0 100644 --- a/packages/sync-service/lib/electric/shapes/consumer.ex +++ b/packages/sync-service/lib/electric/shapes/consumer.ex @@ -270,10 +270,20 @@ defmodule Electric.Shapes.Consumer do end end - def handle_info({ShapeCache.Storage, :flushed, offset_in}, state) do - {state, offset_txn} = State.align_offset_to_txn_boundary(state, offset_in) + def handle_info({ShapeCache.Storage, :flushed, flushed_offset}, state) do + state = + if is_write_unit_txn(state.write_unit) or is_nil(state.pending_txn) do + # We're not currently in the middle of processing a transaction. This flushed offset is either + # from a previously processed transaction or a non-commit fragment of the most recently + # seen transaction. Notify ShapeLogCollector about it immediately. + confirm_flushed_and_notify(state, flushed_offset) + else + # Storage has signaled latest flushed offset in the middle of processing a multi-fragment + # transaction. Save it for later, to be handled when the commit fragment arrives. + updated_offset = more_recent_offset(state.pending_flush_offset, flushed_offset) + %{state | pending_flush_offset: updated_offset} + end - ShapeLogCollector.notify_flushed(state.stack_id, state.shape_handle, offset_txn) {:noreply, state, state.hibernate_after} end @@ -567,7 +577,7 @@ defmodule Electric.Shapes.Consumer do # With write_unit=txn all fragments are buffered until the Commit change is seen. At that # point, a transaction struct is produced from the buffered fragments and is written to # storage. - state.write_unit == State.write_unit_txn() -> + is_write_unit_txn(state.write_unit) -> {txns, transaction_builder} = TransactionBuilder.build(txn_fragment, state.transaction_builder) @@ -597,6 +607,7 @@ defmodule Electric.Shapes.Consumer do defp skip_txn_fragment(state, %TransactionFragment{} = txn_fragment) do %{state | pending_txn: nil} |> consider_flushed(txn_fragment.last_log_offset) + |> clear_pending_flush_offset() end # This function does similar things to do_handle_txn/2 but with the following simplifications: @@ -747,9 +758,10 @@ defmodule Electric.Shapes.Consumer do "No relevant changes written in transaction xid=#{txn.xid}" end) - state = %{state | pending_txn: nil} - consider_flushed(state, txn_fragment.last_log_offset) + %{state | pending_txn: nil} + |> consider_flushed(txn_fragment.last_log_offset) end + |> clear_pending_flush_offset() end def process_buffered_txn_fragments(%State{buffer: buffer} = state) do @@ -1006,6 +1018,31 @@ defmodule Electric.Shapes.Consumer do end end + defp confirm_flushed_and_notify(state, flushed_offset) do + {state, txn_offset} = State.align_offset_to_txn_boundary(state, flushed_offset) + ShapeLogCollector.notify_flushed(state.stack_id, state.shape_handle, txn_offset) + state + end + + # After a pending transaction completes and txn_offset_mapping is populated, + # process the deferred flushed offset (if any). + # + # Even if the most recent transaction is skipped or no changes from it end up satisfying the + # shape's `where` condition, Storage may have signaled a flush offset from the previous transaction + # while we were still processing fragments of the current one. Therefore this function must + # be called any time `state.pending_txn` is reset to nil in a multi-fragment transaction + # processing setting. + defp clear_pending_flush_offset(%{pending_flush_offset: nil} = state), do: state + + defp clear_pending_flush_offset(%{pending_flush_offset: flushed_offset} = state) do + %{state | pending_flush_offset: nil} + |> confirm_flushed_and_notify(flushed_offset) + end + + defp more_recent_offset(nil, offset), do: offset + defp more_recent_offset(offset, nil), do: offset + defp more_recent_offset(offset1, offset2), do: LogOffset.max(offset1, offset2) + defp subscribe(state, action) do case ShapeLogCollector.add_shape(state.stack_id, state.shape_handle, state.shape, action) do :ok -> diff --git a/packages/sync-service/lib/electric/shapes/consumer/state.ex b/packages/sync-service/lib/electric/shapes/consumer/state.ex index b32204d2a9..52c70eaff9 100644 --- a/packages/sync-service/lib/electric/shapes/consumer/state.ex +++ b/packages/sync-service/lib/electric/shapes/consumer/state.ex @@ -42,7 +42,11 @@ defmodule Electric.Shapes.Consumer.State do # Tracks in-progress transaction, initialized when a txn fragment with has_begin?=true is seen. # It is used to check whether the entire txn is visible in the snapshot and to mark it # as flushed in order to handle its remaining fragments appropriately. - pending_txn: nil + pending_txn: nil, + # When a {Storage, :flushed, offset} message arrives during a pending + # transaction, we defer the notification and store the max flushed offset + # here. Multiple deferred notifications are collapsed into a single most recent offset. + pending_flush_offset: nil ] @type pg_snapshot() :: SnapshotQuery.pg_snapshot() @@ -393,6 +397,6 @@ defmodule Electric.Shapes.Consumer.State do ] end - def write_unit_txn, do: @write_unit_txn - def write_unit_txn_fragment, do: @write_unit_txn_fragment + defguard is_write_unit_txn(write_unit) when write_unit == @write_unit_txn + defguard is_write_unit_txn_fragment(write_unit) when write_unit == @write_unit_txn_fragment end diff --git a/packages/sync-service/lib/electric/shapes/dynamic_consumer_supervisor.ex b/packages/sync-service/lib/electric/shapes/dynamic_consumer_supervisor.ex index 031ee57274..b05fe3f788 100644 --- a/packages/sync-service/lib/electric/shapes/dynamic_consumer_supervisor.ex +++ b/packages/sync-service/lib/electric/shapes/dynamic_consumer_supervisor.ex @@ -1,28 +1,51 @@ defmodule Electric.Shapes.DynamicConsumerSupervisor do @moduledoc """ - Responsible for managing shape consumer processes + Responsible for managing shape consumer processes. + + Uses a set of `DynamicSupervisor`s supervised by a parent `DynamicSupervisor` + to take advantage of the fact that `DynamicSupervisor` terminates its + children in parallel rather than one at a time. + + This improves shutdown time because all consumer processes are effectively + terminated simultaneously. """ use DynamicSupervisor require Logger - @doc """ - Returns a child spec for the PartitionSupervisor that starts a pool of - DynamicConsumerSupervisor procecesses to shard child processes across. + import Electric, only: [is_stack_id: 1] - The number of dynamic supervisors is equal to the number of CPU cores. - """ - def child_spec(opts) do - stack_id = Keyword.fetch!(opts, :stack_id) - {name, opts} = Keyword.pop(opts, :name, name(stack_id)) + defmodule PartitionDynamicSupervisor do + @moduledoc false + + use DynamicSupervisor + + def name(stack_id, partition) when is_binary(stack_id) do + Electric.ProcessRegistry.name(stack_id, __MODULE__, partition) + end - # We're overriding Electric.Shapes.DynamicConsumerSupervisor's child_spec() function here - # to make the usage of PartitionSupervisor transparent to the callers. As a consequence, we - # need to call `super()` to obtain the original DynamicSupervisor child_spec() to pass as an option to - # PartitionSupervisor. - PartitionSupervisor.child_spec(child_spec: super(opts), name: name) + def start_link({stack_id, partition}) do + DynamicSupervisor.start_link(__MODULE__, [stack_id: stack_id], + name: name(stack_id, partition) + ) + end + + @impl true + def init(stack_id: stack_id) do + Process.set_label({:consumer_supervisor_partition, stack_id}) + Logger.metadata(stack_id: stack_id) + Electric.Telemetry.Sentry.set_tags_context(stack_id: stack_id) + + DynamicSupervisor.init(strategy: :one_for_one) + end end + # The max number of processes to start per-partition. Found empirically to + # give a reasonable tradeoff between memory usage and shutdown speed. + @target_per_partition 4_000 + + @partition_count_key :partition_count + def name(name) when is_atom(name) do name end @@ -35,44 +58,97 @@ defmodule Electric.Shapes.DynamicConsumerSupervisor do Electric.ProcessRegistry.name(stack_id, __MODULE__) end - # This function will be invoked for each dynamic supervisor process in PartitionSupervisor's - # pool, so we keep these processes unnamed. def start_link(opts) do stack_id = Keyword.fetch!(opts, :stack_id) - DynamicSupervisor.start_link(__MODULE__, stack_id: stack_id) + {name, opts} = Keyword.pop(opts, :name, name(stack_id)) + max_processes = Keyword.get(opts, :max_shapes) || 0 + # use a fixed value for the partition count if its configured, if not then + # calculate based on the max_shapes setting (using @target_per_partition) + # or fallback to the number of schedulers + partitions = Keyword.get(opts, :partitions) || partition_count(max_processes) + + Logger.info("Starting DynamicConsumerSupervisor with #{partitions} partitions") + + with {:ok, supervisor_pid} <- + DynamicSupervisor.start_link(__MODULE__, %{stack_id: stack_id, partitions: partitions}, + name: name + ) do + case start_partition_supervisors(supervisor_pid, stack_id, partitions) do + {:ok, _pids} -> + {:ok, supervisor_pid} + + {:error, _} = error -> + DynamicSupervisor.stop(supervisor_pid, :shutdown) + error + end + end end - def start_shape_consumer(supervisor_ref, config) do - start_child(supervisor_ref, {Electric.Shapes.Consumer, config}) + defp start_partition_supervisors(supervisor_pid, stack_id, partitions) do + Electric.Utils.reduce_while_ok(0..(partitions - 1), [], fn partition, pids -> + with {:ok, pid} <- + DynamicSupervisor.start_child( + supervisor_pid, + Supervisor.child_spec( + {PartitionDynamicSupervisor, {stack_id, partition}}, + id: {:partition, partition} + ) + ) do + {:ok, [pid | pids]} + end + end) end - def start_snapshotter(supervisor_ref, config) do - start_child(supervisor_ref, {Electric.Shapes.Consumer.Snapshotter, config}) + def start_shape_consumer(stack_id, config) when is_stack_id(stack_id) do + start_child(stack_id, {Electric.Shapes.Consumer, config}) end - def start_materializer(supervisor_ref, config) do - start_child(supervisor_ref, {Electric.Shapes.Consumer.Materializer, config}) + def start_snapshotter(stack_id, config) when is_stack_id(stack_id) do + start_child(stack_id, {Electric.Shapes.Consumer.Snapshotter, config}) end - defp start_child(supervisor_ref, {child_module, child_opts} = child_spec) do - %{shape_handle: shape_handle} = child_opts + def start_materializer(stack_id, config) when is_stack_id(stack_id) do + start_child(stack_id, {Electric.Shapes.Consumer.Materializer, config}) + end - routing_key = :erlang.phash2(shape_handle) + defp start_child(stack_id, {child_module, child_opts} = child_spec) do + %{shape_handle: shape_handle} = child_opts Logger.debug(fn -> "Starting #{inspect(child_module)} for #{shape_handle}" end) - DynamicSupervisor.start_child( - {:via, PartitionSupervisor, {name(supervisor_ref), routing_key}}, - child_spec - ) + DynamicSupervisor.start_child(partition_for(stack_id, shape_handle), child_spec) end @impl true - def init(stack_id: stack_id) do + def init(%{stack_id: stack_id, partitions: partitions}) do Process.set_label({:dynamic_consumer_supervisor, stack_id}) Logger.metadata(stack_id: stack_id) Electric.Telemetry.Sentry.set_tags_context(stack_id: stack_id) + table = :ets.new(table(stack_id), [:named_table, :public, read_concurrency: true]) + true = :ets.insert(table, [{@partition_count_key, partitions}]) + DynamicSupervisor.init(strategy: :one_for_one) end + + defp table(stack_id), do: :"Electric.Shapes.DynamicConsumerSupervisor:#{stack_id}" + + defp partition_for(stack_id, shape_handle) do + partitions = :ets.lookup_element(table(stack_id), @partition_count_key, 2) + partition = :erlang.phash2(shape_handle, partitions) + PartitionDynamicSupervisor.name(stack_id, partition) + end + + # we don't always have a value for `max_processes`, in which case just + # default to the number of schedulers + defp partition_count(0) do + System.schedulers_online() + end + + defp partition_count(max_processes) when max_processes > 0 do + max( + System.schedulers_online(), + div(max_processes + @target_per_partition - 1, @target_per_partition) + ) + end end diff --git a/packages/sync-service/lib/electric/shapes/querying.ex b/packages/sync-service/lib/electric/shapes/querying.ex index 2810815031..32fda4a243 100644 --- a/packages/sync-service/lib/electric/shapes/querying.ex +++ b/packages/sync-service/lib/electric/shapes/querying.ex @@ -274,7 +274,15 @@ defmodule Electric.Shapes.Querying do |> pg_coalesce_json_string() end - defp pg_cast_column_to_text(column), do: ~s["#{Utils.escape_quotes(column)}"::text] + defp pg_cast_column_to_text(column) do + escaped = Utils.escape_quotes(column) + col = ~s["#{escaped}"] + # In PostgreSQL, casting bpchar (char(n)) to text strips trailing spaces. + # Use concat() for bpchar columns to preserve the space padding, since + # concat() converts its argument to text without trimming. + ~s[CASE WHEN #{col} IS NULL THEN NULL::text WHEN pg_typeof(#{col}) = 'character'::regtype THEN concat(#{col}, '') ELSE #{col}::text END] + end + defp pg_escape_string_for_json(str), do: ~s[to_json(#{str})::text] defp pg_coalesce_json_string(str), do: ~s[coalesce(#{str} , 'null')] diff --git a/packages/sync-service/lib/electric/stack_supervisor.ex b/packages/sync-service/lib/electric/stack_supervisor.ex index b01d912bb5..d7e297b7d9 100644 --- a/packages/sync-service/lib/electric/stack_supervisor.ex +++ b/packages/sync-service/lib/electric/stack_supervisor.ex @@ -146,7 +146,8 @@ defmodule Electric.StackSupervisor do type: {:or, [:pos_integer, nil]}, default: nil ], - process_spawn_opts: [type: :map, default: %{}] + process_spawn_opts: [type: :map, default: %{}], + consumer_partitions: [type: {:or, [:pos_integer, nil]}, default: nil] ] ], lock_breaker_guard: [ diff --git a/packages/sync-service/package.json b/packages/sync-service/package.json index 270c86748a..64241f935f 100644 --- a/packages/sync-service/package.json +++ b/packages/sync-service/package.json @@ -1,7 +1,7 @@ { "name": "@core/sync-service", "private": true, - "version": "1.4.15", + "version": "1.4.16", "scripts": { "publish:hex": "../../scripts/publish_hex.sh electric", "changeset": "pushd ../..; pnpm changeset; popd" diff --git a/packages/sync-service/test/electric/replication/shape_log_collector/flush_tracker_test.exs b/packages/sync-service/test/electric/replication/shape_log_collector/flush_tracker_test.exs index 6fabe24447..5b2f45655e 100644 --- a/packages/sync-service/test/electric/replication/shape_log_collector/flush_tracker_test.exs +++ b/packages/sync-service/test/electric/replication/shape_log_collector/flush_tracker_test.exs @@ -27,23 +27,7 @@ defmodule Electric.Replication.ShapeLogCollector.FlushTrackerTest do refute_receive {:flush_confirmed, _} end - test "non-commit fragment tracks shapes but does not notify or update last_seen", %{ - tracker: tracker - } do - fragment = %TransactionFragment{ - xid: 1, - lsn: 1, - last_log_offset: LogOffset.new(1, 0), - commit: nil - } - - tracker = handle_txn(tracker, fragment, ["shape1"]) - refute_receive {:flush_confirmed, _} - # Shape is tracked in last_flushed - refute FlushTracker.empty?(tracker) - end - - test "non-commit fragment with no affected shapes is a no-op", %{tracker: tracker} do + test "non-commit fragment raises FunctionClauseError", %{tracker: tracker} do fragment = %TransactionFragment{ xid: 1, lsn: 1, @@ -51,192 +35,20 @@ defmodule Electric.Replication.ShapeLogCollector.FlushTrackerTest do commit: nil } - tracker = handle_txn(tracker, fragment, []) - refute_receive {:flush_confirmed, _} - assert FlushTracker.empty?(tracker) - end - - test "shape tracked by non-commit fragment can be flushed before commit arrives", %{ - tracker: tracker - } do - # Non-commit fragment registers shape - fragment = %TransactionFragment{ - xid: 1, - lsn: 5, - last_log_offset: LogOffset.new(5, 4), - commit: nil - } - - tracker = handle_txn(tracker, fragment, ["shape1"]) - - # Flush notification catches up the shape in last_flushed - tracker = FlushTracker.handle_flush_notification(tracker, "shape1", LogOffset.new(5, 4)) - - # No notification yet — no commit seen - refute_receive {:flush_confirmed, _} - assert FlushTracker.empty?(tracker) - - # Commit arrives with shape1 in affected_shapes (via EventRouter's shapes_in_txn) - # but shape1 has no new changes — only a commit marker. It was already flushed, - # so it should not be re-registered. - tracker = - FlushTracker.handle_txn_fragment( - tracker, - batch(xid: 1, lsn: 5, last_offset: 10), - ["shape1"], - MapSet.new() - ) - - # Shape was skipped, tracker is empty, global offset notified - assert_receive {:flush_confirmed, 5} - assert FlushTracker.empty?(tracker) - end - - test "shape tracked by non-commit and still pending is updated by commit", %{ - tracker: tracker - } do - # Non-commit fragment registers shape - fragment = %TransactionFragment{ - xid: 1, - lsn: 5, - last_log_offset: LogOffset.new(5, 2), - commit: nil - } - - tracker = handle_txn(tracker, fragment, ["shape1"]) - - # Commit arrives — shape is still in last_flushed, so last_sent is updated - # (shapes_with_changes doesn't matter here since shape is already tracked) - tracker = - FlushTracker.handle_txn_fragment( - tracker, - batch(xid: 1, lsn: 5, last_offset: 10), - ["shape1"], - MapSet.new() - ) - - refute FlushTracker.empty?(tracker) - - # Flush at the commit's offset catches up the shape - tracker = - FlushTracker.handle_flush_notification(tracker, "shape1", LogOffset.new(5, 10)) - - assert_receive {:flush_confirmed, 5} - assert FlushTracker.empty?(tracker) - end - - test "shape only in commit (not in non-commit fragments) is tracked normally", %{ - tracker: tracker - } do - # Non-commit fragment for shape1 - fragment = %TransactionFragment{ - xid: 1, - lsn: 5, - last_log_offset: LogOffset.new(5, 2), - commit: nil - } - - tracker = handle_txn(tracker, fragment, ["shape1"]) - - # Commit has both shapes — shape2 has actual changes in the commit fragment - tracker = - FlushTracker.handle_txn_fragment( - tracker, - batch(xid: 1, lsn: 5, last_offset: 10), - ["shape1", "shape2"], - MapSet.new(["shape2"]) - ) - - refute FlushTracker.empty?(tracker) - - # Both shapes need to be flushed - tracker = - FlushTracker.handle_flush_notification(tracker, "shape1", LogOffset.new(5, 10)) - - tracker = - FlushTracker.handle_flush_notification(tracker, "shape2", LogOffset.new(5, 10)) - - assert_receive {:flush_confirmed, 5} - assert FlushTracker.empty?(tracker) + assert_raise FunctionClauseError, fn -> handle_txn(tracker, fragment, ["shape1"]) end end - test "already-flushed shape with new changes in commit is re-tracked", %{ + test "non-commit fragment with no affected shapes raises FunctionClauseError", %{ tracker: tracker } do - # Non-commit fragment registers shape fragment = %TransactionFragment{ xid: 1, - lsn: 5, - last_log_offset: LogOffset.new(5, 4), - commit: nil - } - - tracker = handle_txn(tracker, fragment, ["shape1"]) - - # Flush notification catches up the shape in last_flushed - tracker = FlushTracker.handle_flush_notification(tracker, "shape1", LogOffset.new(5, 4)) - assert FlushTracker.empty?(tracker) - - # Commit arrives — shape1 has NEW changes in the commit fragment - tracker = - FlushTracker.handle_txn_fragment( - tracker, - batch(xid: 1, lsn: 5, last_offset: 10), - ["shape1"], - MapSet.new(["shape1"]) - ) - - # Shape must be re-tracked to ensure commit-fragment writes are flushed - refute FlushTracker.empty?(tracker) - - tracker = - FlushTracker.handle_flush_notification(tracker, "shape1", LogOffset.new(5, 10)) - - assert_receive {:flush_confirmed, 5} - assert FlushTracker.empty?(tracker) - end - - test "multiple non-commit fragments update last_sent progressively", %{ - tracker: tracker - } do - frag1 = %TransactionFragment{ - xid: 1, - lsn: 5, - last_log_offset: LogOffset.new(5, 2), - commit: nil - } - - frag2 = %TransactionFragment{ - xid: 1, - lsn: 5, - last_log_offset: LogOffset.new(5, 5), + lsn: 1, + last_log_offset: LogOffset.new(1, 0), commit: nil } - tracker = - tracker - |> handle_txn(frag1, ["shape1"]) - |> handle_txn(frag2, ["shape1"]) - - # Flushing to the latest non-commit offset catches up the shape - tracker = - FlushTracker.handle_flush_notification(tracker, "shape1", LogOffset.new(5, 5)) - - # No notification — no commit seen - refute_receive {:flush_confirmed, _} - assert FlushTracker.empty?(tracker) - - # Commit with no new changes — shape was flushed, skipped - tracker = - FlushTracker.handle_txn_fragment( - tracker, - batch(xid: 1, lsn: 5, last_offset: 10), - ["shape1"], - MapSet.new() - ) - - assert_receive {:flush_confirmed, 5} - assert FlushTracker.empty?(tracker) + assert_raise FunctionClauseError, fn -> handle_txn(tracker, fragment, []) end end end @@ -460,12 +272,7 @@ defmodule Electric.Replication.ShapeLogCollector.FlushTrackerTest do # Helper: calls handle_txn_fragment with shapes_with_changes defaulting to # all affected shapes (the common case for single-fragment transactions). defp handle_txn(tracker, fragment, affected_shapes) do - FlushTracker.handle_txn_fragment( - tracker, - fragment, - affected_shapes, - MapSet.new(affected_shapes) - ) + FlushTracker.handle_txn_fragment(tracker, fragment, affected_shapes) end defp batch(opts) do diff --git a/packages/sync-service/test/electric/shapes/consumer_test.exs b/packages/sync-service/test/electric/shapes/consumer_test.exs index 6d0fe38cbe..a0abc0b37e 100644 --- a/packages/sync-service/test/electric/shapes/consumer_test.exs +++ b/packages/sync-service/test/electric/shapes/consumer_test.exs @@ -1677,10 +1677,11 @@ defmodule Electric.Shapes.ConsumerTest do test "flush notification for multi-fragment txn is not lost when storage flushes before commit fragment", %{stack_id: stack_id} = ctx do # Regression test for https://github.com/electric-sql/electric/issues/3985 + # Updated for deferred flush notification fix (#4063). # # When a multi-fragment transaction's non-commit fragments are flushed to disk # before the commit fragment is processed by ShapeLogCollector, the flush - # notification was lost because FlushTracker hadn't registered the shape yet. + # notification was lost because FlushTracker wasn't tracking the shape's offsets. # This caused the shape to be stuck in the FlushTracker, blocking # the global flush offset from advancing. {shape_handle, _} = ShapeCache.get_or_create_shape_handle(@shape1, stack_id) @@ -1738,19 +1739,12 @@ defmodule Electric.Shapes.ConsumerTest do assert :ok = ShapeLogCollector.handle_event(fragment1, stack_id) assert :ok = ShapeLogCollector.handle_event(fragment2, stack_id) - flushed_log_offset = fragment2.last_log_offset - - # Matching on a traced call inline to avoid any timing issues that - # Trace.collect_traced_calls() is susceptible to in this case. - assert_receive {:trace, _, :call, - {ShapeLogCollector, :notify_flushed, - [^stack_id, ^shape_handle, ^flushed_log_offset]}}, - @receive_timeout + # With deferred flush notifications, notify_flushed is NOT called + # after non-commit fragments. The flush is deferred until the commit. + assert [] == Support.Trace.collect_traced_calls() # Now send the commit fragment. The commit fragment itself has NO matching # changes for the shape — all changes were in earlier fragments. - # After this, FlushTracker registers the shape but the data was already - # flushed, so no new :flushed message will arrive. commit_fragment = txn_fragment( xid, @@ -1768,8 +1762,120 @@ defmodule Electric.Shapes.ConsumerTest do assert :ok = ShapeLogCollector.handle_event(commit_fragment, ctx.stack_id) assert_receive {^ref, :new_changes, _}, @receive_timeout - # Assert that the flush boundary has advanced which wasn't the case before due to the - # aforementioned bug, + # The deferred flush notification is sent after the commit, aligned + # to the commit fragment's last_log_offset. + commit_offset = commit_fragment.last_log_offset + + assert_receive {:trace, _, :call, + {ShapeLogCollector, :notify_flushed, + [^stack_id, ^shape_handle, ^commit_offset]}}, + @receive_timeout + + # Flush boundary advances. + tx_offset = commit_fragment.last_log_offset.tx_offset + assert_receive {:flush_boundary_updated, ^tx_offset}, @receive_timeout + end + + @tag allow_subqueries: false, with_pure_file_storage_opts: [flush_period: 10_000] + test "flush notification offset is aligned when storage flushes before commit arrives at consumer", + %{stack_id: stack_id} do + # Regression test for https://github.com/electric-sql/electric/issues/4063 + # + # When a non-commit fragment has enough data to trigger a buffer-size + # flush (>= 64KB), the :flushed message is placed in the consumer's + # mailbox during processing. The consumer process ends up handling the :flushed message + # before receiving the commit fragment. But since the offset it sends to FlushTracker + # predates the commit fragment's offset, the FlushTracker keeps the shape in the + # "pending" state and there's no follow-up notification from the consumer that would + # unblock it. + # + # A high flush_period prevents timer-based flushes so the only flush + # comes from the buffer-size trigger, making the test deterministic. + + {shape_handle, _} = ShapeCache.get_or_create_shape_handle(@shape1, stack_id) + :started = ShapeCache.await_snapshot_start(shape_handle, stack_id) + + ref = Shapes.Consumer.register_for_changes(stack_id, shape_handle) + register_as_replication_client(stack_id) + + xid = 11 + lsn = Lsn.from_integer(10) + relevant_change_offset = LogOffset.new(lsn, 0) + + # The fragment has a large shape-relevant record (>64KB) that triggers a + # buffer-size flush during write, PLUS a non-matching record at a higher + # offset. This means the source fragment's last_log_offset is higher than + # the shape's last written offset — just like in production where + # transactions touch multiple tables. + padding = String.duplicate("x", 70_000) + + non_commit_fragment = + txn_fragment( + xid, + lsn, + [ + %Changes.NewRecord{ + relation: {"public", "test_table"}, + record: %{"id" => "1", "value" => padding}, + log_offset: relevant_change_offset + }, + # This change does NOT match shape1 (test_table) but raises the + # fragment's last_log_offset above the shape's written offset. + %Changes.NewRecord{ + relation: {"public", "other_table"}, + record: %{"id" => "2"}, + log_offset: LogOffset.new(lsn, 50) + } + ], + has_begin?: true + ) + + # Commit fragment has only a change for a different table. The consumer + # writes nothing for it but still finalises the pending transaction, + # populating txn_offset_mapping. + commit_fragment = + txn_fragment( + xid, + lsn, + [ + %Changes.NewRecord{ + relation: {"public", "other_table"}, + record: %{"id" => "99"}, + log_offset: LogOffset.new(lsn, 100) + } + ], + has_commit?: true + ) + + # Send non-commit fragment. The large record triggers a buffer flush, + # placing {Storage, :flushed, offset} in the consumer's mailbox. + Support.Trace.trace_shape_log_collector_calls( + pid: Shapes.Consumer.whereis(stack_id, shape_handle), + functions: [:notify_flushed] + ) + + assert :ok = ShapeLogCollector.handle_event(non_commit_fragment, stack_id) + + # With deferred flush notifications, the consumer does NOT call notify_flushed + # after the non-commit fragment. The :flushed message is saved for later. + assert [] == Support.Trace.collect_traced_calls() + + # Send the commit fragment to finalize the transaction. + assert :ok = ShapeLogCollector.handle_event(commit_fragment, stack_id) + + # Consumer has processed the relevant change... + assert_receive {^ref, :new_changes, ^relevant_change_offset}, @receive_timeout + + # The deferred flush notification is sent after the commit with the + # aligned offset (the commit fragment's last_log_offset). + commit_last_log_offset = commit_fragment.last_log_offset + + assert [ + {ShapeLogCollector, :notify_flushed, + [^stack_id, ^shape_handle, ^commit_last_log_offset]} + ] = Support.Trace.collect_traced_calls() + + # Flush boundary advances correctly. tx_offset = commit_fragment.last_log_offset.tx_offset assert_receive {:flush_boundary_updated, ^tx_offset}, @receive_timeout end diff --git a/packages/sync-service/test/electric/shapes/event_router_test.exs b/packages/sync-service/test/electric/shapes/event_router_test.exs index eae7c2b59f..e670348b47 100644 --- a/packages/sync-service/test/electric/shapes/event_router_test.exs +++ b/packages/sync-service/test/electric/shapes/event_router_test.exs @@ -8,6 +8,7 @@ defmodule Electric.Shapes.EventRouterTest do alias Electric.Replication.Changes.TruncatedRelation alias Electric.Replication.Changes.UpdatedRecord alias Electric.Replication.Changes.TransactionFragment + alias Electric.Replication.LogOffset alias Electric.Shapes.EventRouter alias Electric.Shapes.Shape alias Support.StubInspector @@ -96,6 +97,8 @@ defmodule Electric.Shapes.EventRouterTest do {result, _router} = EventRouter.event_by_shape_handle(router, batch) + assert ["s1", "s2"] == result |> Map.keys() |> Enum.sort() + assert %{ "s1" => %TransactionFragment{ has_begin?: true, @@ -275,6 +278,8 @@ defmodule Electric.Shapes.EventRouterTest do {result, _router} = EventRouter.event_by_shape_handle(router, batch) + assert ["s1", "s2", "s3", "s4"] == result |> Map.keys() |> Enum.sort() + assert %{ "s1" => %TransactionFragment{ has_begin?: true, @@ -318,6 +323,8 @@ defmodule Electric.Shapes.EventRouterTest do {result, _router} = EventRouter.event_by_shape_handle(router, batch) + assert ["s1", "s2"] == result |> Map.keys() |> Enum.sort() + assert %{ "s1" => %TransactionFragment{affected_relations: s1_relations}, "s2" => %TransactionFragment{affected_relations: s2_relations} @@ -374,9 +381,8 @@ defmodule Electric.Shapes.EventRouterTest do {result2, _router} = EventRouter.event_by_shape_handle(router, batch2) - assert %{ - "s1" => %TransactionFragment{has_begin?: true, changes: [^insert]} - } = result2 + assert ["s1"] == Map.keys(result2) + assert %{"s1" => %TransactionFragment{has_begin?: true, changes: [^insert]}} = result2 end test "Begin seen once per shape even across multiple batches" do @@ -423,13 +429,14 @@ defmodule Electric.Shapes.EventRouterTest do batch1 = %TransactionFragment{xid: 100, has_begin?: true, changes: [insert1]} {result1, router} = EventRouter.event_by_shape_handle(router, batch1) + assert ["s1"] == Map.keys(result1) assert %{"s1" => %TransactionFragment{has_begin?: true, changes: [^insert1]}} = result1 insert2 = %NewRecord{relation: {"public", "t1"}, record: %{"id" => "2"}} batch2 = %TransactionFragment{xid: 100, has_begin?: false, changes: [insert2]} {result2, _router} = EventRouter.event_by_shape_handle(router, batch2) - + assert ["s2"] == Map.keys(result2) assert %{"s2" => %TransactionFragment{has_begin?: true, changes: [^insert2]}} = result2 end @@ -445,6 +452,7 @@ defmodule Electric.Shapes.EventRouterTest do {result1, router} = EventRouter.event_by_shape_handle(router, batch1) + assert ["s1"] == Map.keys(result1) assert %{"s1" => %TransactionFragment{has_begin?: true, changes: [^insert1]}} = result1 insert2 = %NewRecord{relation: {"public", "t1"}, record: %{"id" => "2"}} @@ -459,6 +467,8 @@ defmodule Electric.Shapes.EventRouterTest do {result2, _router} = EventRouter.event_by_shape_handle(router, batch2) + assert ["s1", "s2"] == result2 |> Map.keys() |> Enum.sort() + assert %{ "s1" => %TransactionFragment{has_begin?: false, commit: ^commit_op, changes: []}, "s2" => %TransactionFragment{ @@ -496,6 +506,100 @@ defmodule Electric.Shapes.EventRouterTest do assert result2 == %{"s1" => batch2} end + test "commit-only fragment for shape when commit has changes only for a different table" do + router = + EventRouter.new() + |> EventRouter.add_shape("s1", Shape.new!("t1", inspector: @inspector)) + |> EventRouter.add_shape("s2", Shape.new!("t2", inspector: @inspector)) + + insert_t1 = %NewRecord{ + relation: {"public", "t1"}, + record: %{"id" => "1"}, + log_offset: LogOffset.new(10, 0) + } + + insert_t2_first = %NewRecord{ + relation: {"public", "t2"}, + record: %{"id" => "2"}, + log_offset: LogOffset.new(10, 2) + } + + batch1 = %TransactionFragment{ + xid: 100, + has_begin?: true, + last_log_offset: LogOffset.new(10, 2), + changes: [insert_t1, insert_t2_first], + change_count: 2 + } + + {result1, router} = EventRouter.event_by_shape_handle(router, batch1) + + # Shape s1 only gets the t1 change but last_log_offset is copied from the txn fragment + batch1_last_offset = LogOffset.new(10, 2) + + assert ["s1", "s2"] == Map.keys(result1) + + assert %{ + "s1" => %TransactionFragment{ + has_begin?: true, + commit: nil, + changes: [^insert_t1], + change_count: 1, + last_log_offset: ^batch1_last_offset + }, + "s2" => %TransactionFragment{ + has_begin?: true, + commit: nil, + changes: [^insert_t2_first], + change_count: 1, + last_log_offset: ^batch1_last_offset + } + } = result1 + + # Commit fragment has only a t2 change + insert_t2_last = %NewRecord{ + relation: {"public", "t2"}, + record: %{"id" => "99"}, + log_offset: LogOffset.new(10, 4) + } + + commit_op = %Commit{commit_timestamp: ~U[2024-01-01 00:00:00Z]} + + batch2 = %TransactionFragment{ + xid: 100, + has_begin?: false, + commit: commit_op, + last_log_offset: LogOffset.new(10, 4), + changes: [insert_t2_last], + change_count: 1 + } + + {result2, _router} = EventRouter.event_by_shape_handle(router, batch2) + + # s1 gets a commit-only fragment: change_count=0, + # and last_log_offset from the commit fragment + batch2_last_offset = LogOffset.new(10, 4) + + assert ["s1", "s2"] == Map.keys(result2) + + assert %{ + "s1" => %TransactionFragment{ + has_begin?: false, + commit: ^commit_op, + changes: [], + change_count: 0, + last_log_offset: ^batch2_last_offset + }, + "s2" => %TransactionFragment{ + has_begin?: false, + commit: ^commit_op, + changes: [^insert_t2_last], + change_count: 1, + last_log_offset: ^batch2_last_offset + } + } = result2 + end + test "transaction state is reset after Commit" do router = EventRouter.new() @@ -594,6 +698,7 @@ defmodule Electric.Shapes.EventRouterTest do batch1 = %TransactionFragment{xid: 100, has_begin?: true, changes: [insert1]} {result1, router} = EventRouter.event_by_shape_handle(router, batch1) + assert ["s1"] == Map.keys(result1) assert %{"s1" => %TransactionFragment{has_begin?: true, changes: [^insert1]}} = result1 insert2 = %NewRecord{relation: {"public", "t1"}, record: %{"id" => "2"}} @@ -602,6 +707,8 @@ defmodule Electric.Shapes.EventRouterTest do {result2, router} = EventRouter.event_by_shape_handle(router, batch2) + assert ["s2", "s3"] == result2 |> Map.keys() |> Enum.sort() + assert %{ "s2" => %TransactionFragment{has_begin?: true, changes: [^insert2]}, "s3" => %TransactionFragment{has_begin?: true, changes: [^insert3]} @@ -619,6 +726,8 @@ defmodule Electric.Shapes.EventRouterTest do {result3, _router} = EventRouter.event_by_shape_handle(router, batch3) + assert ["s1", "s2", "s3"] == result3 |> Map.keys() |> Enum.sort() + assert %{ "s1" => %TransactionFragment{ has_begin?: false, @@ -646,6 +755,7 @@ defmodule Electric.Shapes.EventRouterTest do %TransactionFragment{xid: 100, has_begin?: true, changes: [insert1a, insert2a]} ) + assert ["s1"] == Map.keys(result1) assert %{"s1" => %TransactionFragment{has_begin?: true, changes: [^insert1a]}} = result1 # Shape s2 added mid-transaction - should not receive any events from this transaction @@ -674,6 +784,8 @@ defmodule Electric.Shapes.EventRouterTest do ) # s1 gets its changes + commit, s2 gets nothing (added mid-transaction) + assert ["s1"] == Map.keys(result2) + assert %{ "s1" => %TransactionFragment{ has_begin?: false, @@ -698,6 +810,8 @@ defmodule Electric.Shapes.EventRouterTest do } ) + assert ["s1", "s2"] == result3 |> Map.keys() |> Enum.sort() + assert %{ "s1" => %TransactionFragment{ has_begin?: true, @@ -726,6 +840,7 @@ defmodule Electric.Shapes.EventRouterTest do %TransactionFragment{xid: 100, has_begin?: true, changes: [insert1a, insert2a]} ) + assert ["s1"] == Map.keys(result1) assert %{"s1" => %TransactionFragment{has_begin?: true, changes: [^insert1a]}} = result1 # Shapes s2 and s3 added mid-transaction - neither should receive any events from this @@ -753,6 +868,8 @@ defmodule Electric.Shapes.EventRouterTest do ) # s1 gets its changes + commit, s2 and s3 get nothing (added mid-transaction) + assert ["s1"] == Map.keys(result2) + assert %{ "s1" => %TransactionFragment{ has_begin?: false, @@ -778,6 +895,8 @@ defmodule Electric.Shapes.EventRouterTest do } ) + assert ["s1", "s2", "s3"] == result3 |> Map.keys() |> Enum.sort() + assert %{ "s1" => %TransactionFragment{ has_begin?: true, @@ -812,6 +931,8 @@ defmodule Electric.Shapes.EventRouterTest do %TransactionFragment{xid: 100, has_begin?: true, changes: [insert1a, insert2a]} ) + assert ["s1", "s2"] == result1 |> Map.keys() |> Enum.sort() + assert %{ "s1" => %TransactionFragment{has_begin?: true, changes: [^insert1a]}, "s2" => %TransactionFragment{has_begin?: true, changes: [^insert2a]} @@ -836,6 +957,8 @@ defmodule Electric.Shapes.EventRouterTest do ) # s1 gets nothing (removed), s2 gets its changes + commit + assert ["s2"] == Map.keys(result2) + assert %{ "s2" => %TransactionFragment{ has_begin?: false, @@ -859,6 +982,7 @@ defmodule Electric.Shapes.EventRouterTest do %TransactionFragment{xid: 100, has_begin?: true, changes: [insert1a, insert2a]} ) + assert ["s1"] == Map.keys(result1) assert %{"s1" => %TransactionFragment{has_begin?: true, changes: [^insert1a]}} = result1 # s2 added mid-transaction @@ -879,6 +1003,7 @@ defmodule Electric.Shapes.EventRouterTest do ) # s2 skipped because added mid-transaction + assert ["s1"] == Map.keys(result2) assert %{"s1" => %TransactionFragment{has_begin?: false, changes: [^insert1b]}} = result2 # s2 removed before transaction ends @@ -900,6 +1025,8 @@ defmodule Electric.Shapes.EventRouterTest do ) # s2 removed, so only s1 gets events + assert ["s1"] == Map.keys(result3) + assert %{ "s1" => %TransactionFragment{ has_begin?: false, @@ -924,6 +1051,8 @@ defmodule Electric.Shapes.EventRouterTest do } ) + assert ["s1"] == Map.keys(result4) + assert %{ "s1" => %TransactionFragment{ has_begin?: true, diff --git a/packages/sync-service/test/electric/shapes/querying_test.exs b/packages/sync-service/test/electric/shapes/querying_test.exs index 02b50dae03..ffda11baca 100644 --- a/packages/sync-service/test/electric/shapes/querying_test.exs +++ b/packages/sync-service/test/electric/shapes/querying_test.exs @@ -436,9 +436,134 @@ defmodule Electric.Shapes.QueryingTest do Querying.stream_initial_data(conn, "dummy-stack-id", "dummy-shape-handle", shape) ) end + + test "preserves space padding for char(n) columns in pk-less table", %{db_conn: conn} do + Postgrex.query!( + conn, + """ + CREATE TABLE padded_no_pk ( + code CHAR(6), + name TEXT + ) + """, + [] + ) + + Postgrex.query!( + conn, + "INSERT INTO padded_no_pk VALUES ('ab', 'first'), ('cd', 'second'), (NULL, 'third')", + [] + ) + + shape = Shape.new!("padded_no_pk", inspector: {DirectInspector, conn}) + + assert [ + %{ + key: ~S["public"."padded_no_pk"/"ab "/"first"], + value: %{code: "ab ", name: "first"} + }, + %{ + key: ~S["public"."padded_no_pk"/"cd "/"second"], + value: %{code: "cd ", name: "second"} + }, + %{ + key: ~S["public"."padded_no_pk"/_/"third"], + value: %{code: nil, name: "third"} + } + ] = + decode_stream( + Querying.stream_initial_data(conn, "dummy-stack-id", "dummy-shape-handle", shape) + ) + end + + test "preserves space padding for char(n) columns", %{db_conn: conn} do + Postgrex.query!( + conn, + """ + CREATE TABLE padded ( + id CHAR(8) PRIMARY KEY, + name CHAR(10), + label TEXT + ) + """, + [] + ) + + Postgrex.query!( + conn, + "INSERT INTO padded VALUES ('ab', 'hello', 'world'), ('cd', NULL, 'test')", + [] + ) + + shape = Shape.new!("padded", inspector: {DirectInspector, conn}) + + assert [ + %{ + key: ~S["public"."padded"/"ab "], + value: %{ + id: "ab ", + name: "hello ", + label: "world" + }, + headers: %{operation: "insert", relation: ["public", "padded"]} + }, + %{ + key: ~S["public"."padded"/"cd "], + value: %{ + id: "cd ", + name: nil, + label: "test" + }, + headers: %{operation: "insert", relation: ["public", "padded"]} + } + ] = + decode_stream( + Querying.stream_initial_data(conn, "dummy-stack-id", "dummy-shape-handle", shape) + ) + end end describe "query_move_in/5 with SubqueryMoves.move_in_where_clause/3" do + test "preserves space padding for char(n) join columns", %{db_conn: conn} do + for statement <- [ + "CREATE TABLE parent (id CHAR(8) PRIMARY KEY, value INTEGER)", + "CREATE TABLE child (id SERIAL PRIMARY KEY, value INTEGER, parent_id CHAR(8) REFERENCES parent(id))", + "INSERT INTO parent VALUES ('ab', 1), ('cd', 2), ('ef', 3)", + "INSERT INTO child (value, parent_id) VALUES (4, 'ab'), (5, 'cd'), (6, 'ef')" + ], + do: Postgrex.query!(conn, statement) + + shape = + Shape.new!("child", + where: "parent_id IN (SELECT id FROM parent)", + inspector: {DirectInspector, conn} + ) + |> fill_handles() + + move_in_values = ["ab ", "cd "] + + assert {where, params} = + SubqueryMoves.move_in_where_clause( + shape, + hd(shape.shape_dependencies_handles), + move_in_values + ) + + assert [ + %{value: %{parent_id: "ab "}}, + %{value: %{parent_id: "cd "}} + ] = + Querying.query_move_in( + conn, + "dummy-stack-id", + "dummy-shape-handle", + shape, + {where, params} + ) + |> Enum.map(fn [_key, _tags, json] -> json end) + |> decode_stream() + end + test "builds the correct query which executes", %{db_conn: conn} do for statement <- [ "CREATE TABLE parent (id SERIAL PRIMARY KEY, value INTEGER)", diff --git a/packages/sync-service/test/support/component_setup.ex b/packages/sync-service/test/support/component_setup.ex index 55dd2ef312..62c6ef7377 100644 --- a/packages/sync-service/test/support/component_setup.ex +++ b/packages/sync-service/test/support/component_setup.ex @@ -294,7 +294,7 @@ defmodule Support.ComponentSetup do defp start_consumer_supervisor(ctx) do consumer_supervisor = :"consumer_supervisor_#{full_test_name(ctx)}" - {Electric.Shapes.DynamicConsumerSupervisor, [stack_id: ctx.stack_id]} + {Electric.Shapes.DynamicConsumerSupervisor, [stack_id: ctx.stack_id, partitions: 1]} |> Supervisor.child_spec(id: consumer_supervisor, restart: :temporary) |> start_supervised!() diff --git a/packages/typescript-client/CHANGELOG.md b/packages/typescript-client/CHANGELOG.md index 83b4e9ab57..5d37ab3b47 100644 --- a/packages/typescript-client/CHANGELOG.md +++ b/packages/typescript-client/CHANGELOG.md @@ -1,5 +1,11 @@ # @electric-sql/client +## 1.5.14 + +### Patch Changes + +- deb7c32: Add move-in event support to the TypeScript client. Rename `MoveOutPattern` to `MovePattern` (with a deprecated alias for backwards compatibility), extend `EventMessage` to accept both `move-out` and `move-in` events, and add `active_conditions` field to `ChangeMessage` headers. + ## 1.5.13 ### Patch Changes diff --git a/packages/typescript-client/package.json b/packages/typescript-client/package.json index 5670263d50..fa506d9e21 100644 --- a/packages/typescript-client/package.json +++ b/packages/typescript-client/package.json @@ -1,7 +1,7 @@ { "name": "@electric-sql/client", "description": "Postgres everywhere - your data, in sync, wherever you need it.", - "version": "1.5.13", + "version": "1.5.14", "author": "ElectricSQL team and contributors.", "bugs": { "url": "https://github.com/electric-sql/electric/issues" diff --git a/packages/typescript-client/src/types.ts b/packages/typescript-client/src/types.ts index 414fb1c563..a4cff5bee5 100644 --- a/packages/typescript-client/src/types.ts +++ b/packages/typescript-client/src/types.ts @@ -60,13 +60,16 @@ export type Operation = `insert` | `update` | `delete` export type MoveTag = string /** - * A move-out pattern is a position and a value. The position is the index of the column - * that is being moved out. The value is the value of the column that is being moved out. + * A move pattern is a position and a value. The position is the index of the column + * involved in the move. The value is the value of that column. * * Tag width and value order is fixed for a given shape, so the client can determine * which tags match this pattern. */ -export type MoveOutPattern = { pos: number; value: string } +export type MovePattern = { pos: number; value: string } + +/** @deprecated Use {@link MovePattern} instead */ +export type MoveOutPattern = MovePattern /** * Serialized expression types for structured subset queries. @@ -125,7 +128,7 @@ export type ControlMessage = { } export type EventMessage = { - headers: Header & { event: `move-out`; patterns: MoveOutPattern[] } + headers: Header & { event: `move-out` | `move-in`; patterns: MovePattern[] } } export type ChangeMessage = Row> = { @@ -138,6 +141,7 @@ export type ChangeMessage = Row> = { /** Tags will always be present for changes if the shape has a subquery in its where clause, and are omitted otherwise.*/ tags?: MoveTag[] removed_tags?: MoveTag[] + active_conditions?: boolean[] } } diff --git a/packages/y-electric/CHANGELOG.md b/packages/y-electric/CHANGELOG.md index a95c3c0a1d..d8204682f7 100644 --- a/packages/y-electric/CHANGELOG.md +++ b/packages/y-electric/CHANGELOG.md @@ -1,5 +1,12 @@ # @electric-sql/y-electric +## 0.1.40 + +### Patch Changes + +- Updated dependencies [deb7c32] + - @electric-sql/client@1.5.14 + ## 0.1.39 ### Patch Changes diff --git a/packages/y-electric/package.json b/packages/y-electric/package.json index 7c73cfe292..d22f69dc88 100644 --- a/packages/y-electric/package.json +++ b/packages/y-electric/package.json @@ -1,6 +1,6 @@ { "name": "@electric-sql/y-electric", - "version": "0.1.39", + "version": "0.1.40", "description": "YJS network provider for ElectricSQL", "author": "ElectricSQL team and contributors.", "bugs": { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 1a64de27ac..311e5caa60 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1011,7 +1011,7 @@ importers: examples/tanstack-db-expo-starter: dependencies: '@electric-sql/client': - specifier: 1.5.13 + specifier: 1.5.14 version: link:../../packages/typescript-client '@expo/metro-runtime': specifier: ~5.0.4 @@ -7691,6 +7691,7 @@ packages: '@xmldom/xmldom@0.8.10': resolution: {integrity: sha512-2WALfTl4xo2SkGCYRt6rDTFfk9R1czmBvUQy12gK2KuRKIpWEhcbbzy8EZXtz/jkRqHX8bFEc6FC1HjX4TUWYw==} engines: {node: '>=10.0.0'} + deprecated: this version has critical issues, please update to the latest version '@zxing/text-encoding@0.9.0': resolution: {integrity: sha512-U/4aVJ2mxI0aDNI8Uq0wEhMgY+u4CNtEb0om3+y3+niDAsoTCOB33UF0sxpzqzdqXLqmvc+vZyAt4O8pPdfkwA==} diff --git a/website/CHANGELOG.md b/website/CHANGELOG.md index 7d70b9da30..26e852a82c 100644 --- a/website/CHANGELOG.md +++ b/website/CHANGELOG.md @@ -1,5 +1,11 @@ # @electric-sql/docs +## 0.0.8 + +### Patch Changes + +- d89be52: Document new ELECTRIC_CONSUMER_PARTITIONS environment variable + ## 0.0.7 ### Patch Changes diff --git a/website/blog/posts/2026-03-31-yjs-durable-streams-on-electric-cloud.md b/website/blog/posts/2026-03-31-yjs-durable-streams-on-electric-cloud.md new file mode 100644 index 0000000000..c0e1f8503c --- /dev/null +++ b/website/blog/posts/2026-03-31-yjs-durable-streams-on-electric-cloud.md @@ -0,0 +1,95 @@ +--- +title: 'Yjs CRDTs over HTTP on Durable Streams' +description: >- + We've released a new Yjs provider built on Durable Streams — sync fan-out and fast catch-up from the edge for collaborative and agentic systems. Now live on Electric Cloud. +excerpt: >- + We've released a new Yjs provider built on Durable Streams — sync fan-out and fast catch-up from the edge for collaborative and agentic systems. Now live on Electric Cloud. +authors: [balegas] +image: /img/blog/yjs-durable-streams-on-electric-cloud/header.png +tags: [durable-streams, cloud, release, sync, collaboration] +outline: [2, 3] +post: true +published: true +--- + +[Yjs](https://yjs.dev) is the de facto library for collaborative editing on the web — battle-proven, CRDT-based, and powering tools like [TipTap](https://tiptap.dev), [CodeMirror](https://codemirror.net), and [BlockNote](https://www.blocknotejs.org/). Today we're releasing [`y-durable-streams`](https://www.npmjs.com/package/@durable-streams/y-durable-streams) — a new Yjs provider built on [Durable Streams](/primitives/durable-streams), now live on [Electric Cloud](/cloud). It brings built-in persistence, compaction, and real-time presence to collaborative apps and agentic systems. + +>[!info] 🚀  Try it now +>[Create a Yjs service](https://dashboard.electric-sql.cloud/?intent=create&serviceType=yjs), see the [integration docs](https://durablestreams.com/yjs), [source code](https://github.com/durable-streams/durable-streams/tree/main/packages/y-durable-streams), and [demo app](https://github.com/balegas/territory-wars). + +## Yjs on Durable Streams + +[Durable Streams](/primitives/durable-streams) is an open HTTP protocol for persistent, resumable, real-time streams. Data is durably stored, synced over plain HTTP, and cacheable at the edge. + +Most Yjs setups rely on WebSocket relay servers that maintain persistent point-to-point connections to sync changes to clients in real time. As agentic systems bring more participants into collaborative documents, they challenge the scalability of these setups. + +Durable Streams use a fan-out architecture for syncing changes in real time. Write changes to a log once and sync them via an edge cache or CDN to any number of connected clients. + +## How it works + +Every document (CRDT) is backed by its own durable stream — a persistent, append-only log. You POST edits to the stream and subscribe to real-time updates via SSE or long-polling. This is the primary channel for syncing live changes to connected clients. + +As updates accumulate, the protocol compacts them into **snapshots** — immutable, point-in-time representations of the document. When a new client opens the document, it fetches the latest snapshot. As new snapshots are generated, the protocol directs clients to the latest one and garbage-collects old ones. + +Presence information flows through dedicated **awareness streams**, separate from the document stream. Awareness data is ephemeral, so these streams have a built-in TTL that automatically cleans them up when there are no active clients. + +For the full details, see the [Yjs Durable Streams Protocol](https://github.com/durable-streams/durable-streams/blob/main/packages/y-durable-streams/YJS-PROTOCOL.md) specification. + +## Demo + +Try [Territory Wars](/demos/territory-wars) — a multiplayer territory capture game running `y-durable-streams` live on Electric Cloud. The game board is a Yjs Y.Map where each cell is a last-writer-wins register. Players move to claim cells and enclose territory. Player presence is tracked via awareness streams. Game state is managed via [StreamDB](/blog/2026/03/26/stream-db). + +## Get started + +Here's how to set up a collaborative text editor — create a Yjs document with awareness and point it at your endpoint: + +```typescript +import { YjsProvider } from '@durable-streams/y-durable-streams' +import { Awareness } from 'y-protocols/awareness' +import * as Y from 'yjs' + +const doc = new Y.Doc() +const awareness = new Awareness(doc) + +const provider = new YjsProvider({ + doc, + awareness, + baseUrl: 'https://api.electric-sql.cloud/v1/stream/svc-your-service', + docId: 'my-document', +}) +``` + +Then wire it into your editor. Here's an example with TipTap: + +```typescript +import { useEditor, EditorContent } from '@tiptap/react' +import StarterKit from '@tiptap/starter-kit' +import Collaboration from '@tiptap/extension-collaboration' +import CollaborationCursor from '@tiptap/extension-collaboration-cursor' + +const editor = useEditor({ + extensions: [ + StarterKit.configure({ history: false }), + Collaboration.configure({ document: doc }), + CollaborationCursor.configure({ provider }), + ], +}) +``` + +The provider handles sync, compaction, and awareness. Cursors, selections, and user presence work out of the box — every client that connects to the same `docId` sees the same document, in real time. + +Clone the [demo app](https://github.com/durable-streams/durable-streams/tree/main/examples/yjs-demo) to see a working example, or drop the provider into your existing Yjs project. + +## No lock-in + +The entire protocol is [documented](https://github.com/durable-streams/durable-streams/blob/main/packages/y-durable-streams/YJS-PROTOCOL.md) and ships with a conformance test suite you can run against any implementation. Self-host it, switch providers, or build your own compatible server — your documents are yours. + +Electric Cloud implements the protocol faithfully — no proprietary extensions, no vendor-specific APIs. It's the fastest way to get started. + +## Next steps + +- [Create a Yjs service](https://dashboard.electric-sql.cloud/?intent=create&serviceType=yjs) on Electric Cloud +- [Integration docs](https://durablestreams.com/yjs) and [protocol spec](https://github.com/durable-streams/durable-streams/blob/main/packages/y-durable-streams/YJS-PROTOCOL.md) +- [Territory Wars demo](https://github.com/balegas/territory-wars) and [collaborative editor example](https://github.com/durable-streams/durable-streams/tree/main/examples/yjs-demo) on GitHub + +Join us on [Discord](https://discord.electric-sql.com) with any questions. diff --git a/website/demos/territory-wars.md b/website/demos/territory-wars.md new file mode 100644 index 0000000000..b43c7072fe --- /dev/null +++ b/website/demos/territory-wars.md @@ -0,0 +1,22 @@ +--- +title: Territory Wars +description: >- + Multiplayer territory capture game built with Yjs CRDTs on Durable Streams. +deployed_url: /demos/territory-wars/index.html +source_url: https://github.com/balegas/territory-wars +image: /img/demos/territory-wars-screenshot.png +demo: true +order: 5 +--- + +# Territory Wars + +Multiplayer territory capture game built with [Yjs](https://yjs.dev) CRDTs on [Durable Streams](/primitives/durable-streams). + + + +## How it works + +The game board is a Yjs Y.Map where each cell is a last-writer-wins register. Players move to claim cells and enclose territory. Player presence is tracked via awareness streams. Game state is managed via [StreamDB](/blog/2026/03/26/stream-db). Built with [`y-durable-streams`](https://www.npmjs.com/package/@durable-streams/y-durable-streams) on [Durable Streams](/primitives/durable-streams). + + diff --git a/website/docs/api/config.md b/website/docs/api/config.md index 2333c33096..74fc527d5b 100644 --- a/website/docs/api/config.md +++ b/website/docs/api/config.md @@ -411,6 +411,17 @@ This replaces the previous `ELECTRIC_EXPERIMENTAL_MAX_SHAPES` environment variab +### ELECTRIC_CONSUMER_PARTITIONS + + + +Consumer processes are partitioned across some number of supervisors to improve launch and shutdown time. If `ELECTRIC_MAX_SHAPES` is set the number of partitions will scale to fit this maximum but if not, it defaults to the number of CPU cores. If you want to improve shutdown performance without setting an upper limit on the number of shapes, then set this to roughly your expected number of shapes / 4000. + + + ## Feature Flags Feature flags enable experimental or advanced features that are not yet enabled by default in production. diff --git a/website/package.json b/website/package.json index 304ca56e68..ccf22db74b 100644 --- a/website/package.json +++ b/website/package.json @@ -1,7 +1,7 @@ { "name": "@electric-sql/docs", "private": true, - "version": "0.0.7", + "version": "0.0.8", "scripts": { "test": "vitest run", "test:watch": "vitest", diff --git a/website/public/demos/territory-wars/assets/index-CJXmzTYg.js b/website/public/demos/territory-wars/assets/index-CJXmzTYg.js new file mode 100644 index 0000000000..06ced2270e --- /dev/null +++ b/website/public/demos/territory-wars/assets/index-CJXmzTYg.js @@ -0,0 +1,44 @@ +(function(){const t=document.createElement(`link`).relList;if(t&&t.supports&&t.supports(`modulepreload`))return;for(const l of document.querySelectorAll(`link[rel="modulepreload"]`))r(l);new MutationObserver(l=>{for(const o of l)if(o.type===`childList`)for(const u of o.addedNodes)u.tagName===`LINK`&&u.rel===`modulepreload`&&r(u)}).observe(document,{childList:!0,subtree:!0});function i(l){const o={};return l.integrity&&(o.integrity=l.integrity),l.referrerPolicy&&(o.referrerPolicy=l.referrerPolicy),l.crossOrigin===`use-credentials`?o.credentials=`include`:l.crossOrigin===`anonymous`?o.credentials=`omit`:o.credentials=`same-origin`,o}function r(l){if(l.ep)return;l.ep=!0;const o=i(l);fetch(l.href,o)}})();function fC(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,`default`)?n.default:n}var xh={exports:{}},Ga={};var H0;function hC(){if(H0)return Ga;H0=1;var n=Symbol.for(`react.transitional.element`),t=Symbol.for(`react.fragment`);function i(r,l,o){var u=null;if(o!==void 0&&(u=``+o),l.key!==void 0&&(u=``+l.key),`key`in l){o={};for(var d in l)d!==`key`&&(o[d]=l[d])}else o=l;return l=o.ref,{$$typeof:n,type:r,key:u,ref:l!==void 0?l:null,props:o}}return Ga.Fragment=t,Ga.jsx=i,Ga.jsxs=i,Ga}var q0;function dC(){return q0||(q0=1,xh.exports=hC()),xh.exports}var F=dC(),_h={exports:{}},Ya={},Th={exports:{}},Ah={};var K0;function pC(){return K0||(K0=1,(function(n){function t(k,I){var Z=k.length;k.push(I);t:for(;0>>1,ft=k[it];if(0>>1;itl(Y,Z))Ql(ot,Y)?(k[it]=ot,k[Q]=Z,it=Q):(k[it]=Y,k[B]=Z,it=B);else if(Ql(ot,Z))k[it]=ot,k[Q]=Z,it=Q;else break t}}return I}function l(k,I){var Z=k.sortIndex-I.sortIndex;return Z!==0?Z:k.id-I.id}if(n.unstable_now=void 0,typeof performance==`object`&&typeof performance.now==`function`){var o=performance;n.unstable_now=function(){return o.now()}}else{var u=Date,d=u.now();n.unstable_now=function(){return u.now()-d}}var p=[],g=[],y=1,m=null,v=3,w=!1,b=!1,E=!1,_=!1,j=typeof setTimeout==`function`?setTimeout:null,O=typeof clearTimeout==`function`?clearTimeout:null,A=typeof setImmediate<`u`?setImmediate:null;function M(k){for(var I=i(g);I!==null;){if(I.callback===null)r(g);else if(I.startTime<=k)r(g),I.sortIndex=I.expirationTime,t(p,I);else break;I=i(g)}}function G(k){if(E=!1,M(k),!b)if(i(p)!==null)b=!0,q||(q=!0,nt());else{var I=i(g);I!==null&&dt(G,I.startTime-k)}}var q=!1,K=-1,W=5,et=-1;function X(){return _?!0:!(n.unstable_now()-etk&&X());){var it=m.callback;if(typeof it==`function`){m.callback=null,v=m.priorityLevel;var ft=it(m.expirationTime<=k);if(k=n.unstable_now(),typeof ft==`function`){m.callback=ft,M(k),I=!0;break e}m===i(p)&&r(p),M(k)}else r(p);m=i(p)}if(m!==null)I=!0;else{var T=i(g);T!==null&&dt(G,T.startTime-k),I=!1}}break t}finally{m=null,v=Z,w=!1}I=void 0}}finally{I?nt():q=!1}}}var nt;if(typeof A==`function`)nt=function(){A(at)};else if(typeof MessageChannel<`u`){var bt=new MessageChannel,Lt=bt.port2;bt.port1.onmessage=at,nt=function(){Lt.postMessage(null)}}else nt=function(){j(at,0)};function dt(k,I){K=j(function(){k(n.unstable_now())},I)}n.unstable_IdlePriority=5,n.unstable_ImmediatePriority=1,n.unstable_LowPriority=4,n.unstable_NormalPriority=3,n.unstable_Profiling=null,n.unstable_UserBlockingPriority=2,n.unstable_cancelCallback=function(k){k.callback=null},n.unstable_forceFrameRate=function(k){0>k||125it?(k.sortIndex=Z,t(g,k),i(p)===null&&k===i(g)&&(E?(O(K),K=-1):E=!0,dt(G,Z-it))):(k.sortIndex=ft,t(p,k),b||w||(b=!0,q||(q=!0,nt()))),k},n.unstable_shouldYield=X,n.unstable_wrapCallback=function(k){var I=v;return function(){var Z=v;v=I;try{return k.apply(this,arguments)}finally{v=Z}}}})(Ah)),Ah}var V0;function gC(){return V0||(V0=1,Th.exports=pC()),Th.exports}var Oh={exports:{}},yt={};var $0;function yC(){if($0)return yt;$0=1;var n=Symbol.for(`react.transitional.element`),t=Symbol.for(`react.portal`),i=Symbol.for(`react.fragment`),r=Symbol.for(`react.strict_mode`),l=Symbol.for(`react.profiler`),o=Symbol.for(`react.consumer`),u=Symbol.for(`react.context`),d=Symbol.for(`react.forward_ref`),p=Symbol.for(`react.suspense`),g=Symbol.for(`react.memo`),y=Symbol.for(`react.lazy`),m=Symbol.for(`react.activity`),v=Symbol.iterator;function w(T){return T===null||typeof T!=`object`?null:(T=v&&T[v]||T[`@@iterator`],typeof T==`function`?T:null)}var b={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},E=Object.assign,_={};function j(T,B,Y){this.props=T,this.context=B,this.refs=_,this.updater=Y||b}j.prototype.isReactComponent={},j.prototype.setState=function(T,B){if(typeof T!=`object`&&typeof T!=`function`&&T!=null)throw Error(`takes an object of state variables to update or a function which returns an object of state variables.`);this.updater.enqueueSetState(this,T,B,`setState`)},j.prototype.forceUpdate=function(T){this.updater.enqueueForceUpdate(this,T,`forceUpdate`)};function O(){}O.prototype=j.prototype;function A(T,B,Y){this.props=T,this.context=B,this.refs=_,this.updater=Y||b}var M=A.prototype=new O;M.constructor=A,E(M,j.prototype),M.isPureReactComponent=!0;var G=Array.isArray;function q(){}var K={H:null,A:null,T:null,S:null},W=Object.prototype.hasOwnProperty;function et(T,B,Y){var Q=Y.ref;return{$$typeof:n,type:T,key:B,ref:Q!==void 0?Q:null,props:Y}}function X(T,B){return et(T.type,B,T.props)}function at(T){return typeof T==`object`&&T!==null&&T.$$typeof===n}function nt(T){var B={"=":`=0`,":":`=2`};return`$`+T.replace(/[=:]/g,function(Y){return B[Y]})}var bt=/\/+/g;function Lt(T,B){return typeof T==`object`&&T!==null&&T.key!=null?nt(``+T.key):B.toString(36)}function dt(T){switch(T.status){case`fulfilled`:return T.value;case`rejected`:throw T.reason;default:switch(typeof T.status==`string`?T.then(q,q):(T.status=`pending`,T.then(function(B){T.status===`pending`&&(T.status=`fulfilled`,T.value=B)},function(B){T.status===`pending`&&(T.status=`rejected`,T.reason=B)})),T.status){case`fulfilled`:return T.value;case`rejected`:throw T.reason}}throw T}function k(T,B,Y,Q,ot){var st=typeof T;(st===`undefined`||st===`boolean`)&&(T=null);var mt=!1;if(T===null)mt=!0;else switch(st){case`bigint`:case`string`:case`number`:mt=!0;break;case`object`:switch(T.$$typeof){case n:case t:mt=!0;break;case y:return mt=T._init,k(mt(T._payload),B,Y,Q,ot)}}if(mt)return ot=ot(T),mt=Q===``?`.`+Lt(T,0):Q,G(ot)?(Y=``,mt!=null&&(Y=mt.replace(bt,`$&/`)+`/`),k(ot,B,Y,``,function(an){return an})):ot!=null&&(at(ot)&&(ot=X(ot,Y+(ot.key==null||T&&T.key===ot.key?``:(``+ot.key).replace(bt,`$&/`)+`/`)+mt)),B.push(ot)),1;mt=0;var Ut=Q===``?`.`:Q+`:`;if(G(T))for(var wt=0;wt`u`||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!=`function`))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(t){console.error(t)}}return n(),Rh.exports=mC(),Rh.exports}var Q0;function vC(){if(Q0)return Ya;Q0=1;var n=gC(),t=Jd(),i=SC();function r(e){var s=`https://react.dev/errors/`+e;if(1ft||(e.current=it[ft],it[ft]=null,ft--)}function Y(e,s){ft++,it[ft]=e.current,e.current=s}var Q=T(null),ot=T(null),st=T(null),mt=T(null);function Ut(e,s){switch(Y(st,s),Y(ot,e),Y(Q,null),s.nodeType){case 9:case 11:e=(e=s.documentElement)&&(e=e.namespaceURI)?c0(e):0;break;default:if(e=s.tagName,s=s.namespaceURI)s=c0(s),e=u0(s,e);else switch(e){case`svg`:e=1;break;case`math`:e=2;break;default:e=0}}B(Q),Y(Q,e)}function wt(){B(Q),B(ot),B(st)}function an(e){e.memoizedState!==null&&Y(mt,e);var s=Q.current,a=u0(s,e.type);s!==a&&(Y(ot,e),Y(Q,a))}function $e(e){ot.current===e&&(B(Q),B(ot)),mt.current===e&&(B(mt),qa._currentValue=Z)}var Ps,ki;function Te(e){if(Ps===void 0)try{throw Error()}catch(a){var s=a.stack.trim().match(/\n( *(at )?)/);Ps=s&&s[1]||``,ki=-1)`:-1f||x[c]!==z[f]){var H=` +`+x[c].replace(` at new `,` at `);return e.displayName&&H.includes(``)&&(H=H.replace(``,e.displayName)),H}while(1<=c&&0<=f);break}}}finally{ti=!1,Error.prepareStackTrace=a}return(a=e?e.displayName||e.name:``)?Te(a):``}function uu(e,s){switch(e.tag){case 26:case 27:case 5:return Te(e.type);case 16:return Te(`Lazy`);case 13:return e.child!==s&&s!==null?Te(`Suspense Fallback`):Te(`Suspense`);case 19:return Te(`SuspenseList`);case 0:case 15:return Jr(e.type,!1);case 11:return Jr(e.type.render,!1);case 1:return Jr(e.type,!0);case 31:return Te(`Activity`);default:return``}}function Ui(e){try{var s=``,a=null;do s+=uu(e,a),a=e,e=e.return;while(e);return s}catch(c){return` +Error generating stack: `+c.message+` +`+c.stack}}var Zr=Object.prototype.hasOwnProperty,tt=n.unstable_scheduleCallback,P=n.unstable_cancelCallback,gt=n.unstable_shouldYield,pt=n.unstable_requestPaint,ht=n.unstable_now,Qt=n.unstable_getCurrentPriorityLevel,De=n.unstable_ImmediatePriority,Ge=n.unstable_UserBlockingPriority,Ye=n.unstable_NormalPriority,Gn=n.unstable_LowPriority,zi=n.unstable_IdlePriority,Wr=n.log,Qw=n.unstable_setDisableYieldValue,Pr=null,Fe=null;function vs(e){if(typeof Wr==`function`&&Qw(e),Fe&&typeof Fe.setStrictMode==`function`)try{Fe.setStrictMode(Pr,e)}catch{}}var Qe=Math.clz32?Math.clz32:Zw,Xw=Math.log,Jw=Math.LN2;function Zw(e){return e>>>=0,e===0?32:31-(Xw(e)/Jw|0)|0}var Dl=256,Ml=262144,kl=4194304;function ei(e){var s=e&42;if(s!==0)return s;switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return e&261888;case 262144:case 524288:case 1048576:case 2097152:return e&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return e&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return e}}function Ul(e,s,a){var c=e.pendingLanes;if(c===0)return 0;var f=0,h=e.suspendedLanes,S=e.pingedLanes;e=e.warmLanes;var C=c&134217727;return C!==0?(c=C&~h,c!==0?f=ei(c):(S&=C,S!==0?f=ei(S):a||(a=C&~e,a!==0&&(f=ei(a))))):(C=c&~h,C!==0?f=ei(C):S!==0?f=ei(S):a||(a=c&~e,a!==0&&(f=ei(a)))),f===0?0:s!==0&&s!==f&&(s&h)===0&&(h=f&-f,a=s&-s,h>=a||h===32&&(a&4194048)!==0)?s:f}function ta(e,s){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&s)===0}function Ww(e,s){switch(e){case 1:case 2:case 4:case 8:case 64:return s+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return s+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function $p(){var e=kl;return kl<<=1,(kl&62914560)===0&&(kl=4194304),e}function fu(e){for(var s=[],a=0;31>a;a++)s.push(e);return s}function ea(e,s){e.pendingLanes|=s,s!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function Pw(e,s,a,c,f,h){var S=e.pendingLanes;e.pendingLanes=a,e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0,e.expiredLanes&=a,e.entangledLanes&=a,e.errorRecoveryDisabledLanes&=a,e.shellSuspendCounter=0;var C=e.entanglements,x=e.expirationTimes,z=e.hiddenUpdates;for(a=S&~a;0`u`)return null;try{return e.activeElement||e.body}catch{return e.body}}var rE=/[\n"\\]/g;function on(e){return e.replace(rE,function(s){return`\\`+s.charCodeAt(0).toString(16)+` `})}function mu(e,s,a,c,f,h,S,C){e.name=``,S!=null&&typeof S!=`function`&&typeof S!=`symbol`&&typeof S!=`boolean`?e.type=S:e.removeAttribute(`type`),s!=null?S===`number`?(s===0&&e.value===``||e.value!=s)&&(e.value=``+ln(s)):e.value!==``+ln(s)&&(e.value=``+ln(s)):S!==`submit`&&S!==`reset`||e.removeAttribute(`value`),s!=null?Su(e,S,ln(s)):a!=null?Su(e,S,ln(a)):c!=null&&e.removeAttribute(`value`),f==null&&h!=null&&(e.defaultChecked=!!h),f!=null&&(e.checked=f&&typeof f!=`function`&&typeof f!=`symbol`),C!=null&&typeof C!=`function`&&typeof C!=`symbol`&&typeof C!=`boolean`?e.name=``+ln(C):e.removeAttribute(`name`)}function sg(e,s,a,c,f,h,S,C){if(h!=null&&typeof h!=`function`&&typeof h!=`symbol`&&typeof h!=`boolean`&&(e.type=h),s!=null||a!=null){if(!(h!==`submit`&&h!==`reset`||s!=null)){yu(e);return}a=a!=null?``+ln(a):``,s=s!=null?``+ln(s):a,C||s===e.value||(e.value=s),e.defaultValue=s}c=c??f,c=typeof c!=`function`&&typeof c!=`symbol`&&!!c,e.checked=C?e.checked:!!c,e.defaultChecked=!!c,S!=null&&typeof S!=`function`&&typeof S!=`symbol`&&typeof S!=`boolean`&&(e.name=S),yu(e)}function Su(e,s,a){s===`number`&&jl(e.ownerDocument)===e||e.defaultValue===``+a||(e.defaultValue=``+a)}function Hi(e,s,a,c){if(e=e.options,s){s={};for(var f=0;f`u`||typeof window.document>`u`||typeof window.document.createElement>`u`),Cu=!1;if(Qn)try{var ra={};Object.defineProperty(ra,`passive`,{get:function(){Cu=!0}}),window.addEventListener(`test`,ra,ra),window.removeEventListener(`test`,ra,ra)}catch{Cu=!1}var ws=null,xu=null,Ll=null;function ug(){if(Ll)return Ll;var e,s=xu,a=s.length,c,f=`value`in ws?ws.value:ws.textContent,h=f.length;for(e=0;e=oa),yg=` `,mg=!1;function Sg(e,s){switch(e){case`keyup`:return UE.indexOf(s.keyCode)!==-1;case`keydown`:return s.keyCode!==229;case`keypress`:case`mousedown`:case`focusout`:return!0;default:return!1}}function vg(e){return e=e.detail,typeof e==`object`&&`data`in e?e.data:null}var $i=!1;function NE(e,s){switch(e){case`compositionend`:return vg(s);case`keypress`:return s.which!==32?null:(mg=!0,yg);case`textInput`:return e=s.data,e===yg&&mg?null:e;default:return null}}function jE(e,s){if($i)return e===`compositionend`||!Ru&&Sg(e,s)?(e=ug(),Ll=xu=ws=null,$i=!1,e):null;switch(e){case`paste`:return null;case`keypress`:if(!(s.ctrlKey||s.altKey||s.metaKey)||s.ctrlKey&&s.altKey){if(s.char&&1=s)return{node:a,offset:s-e};e=c}t:{for(;a;){if(a.nextSibling){a=a.nextSibling;break t}a=a.parentNode}a=void 0}a=Ag(a)}}function Rg(e,s){return e&&s?e===s?!0:e&&e.nodeType===3?!1:s&&s.nodeType===3?Rg(e,s.parentNode):`contains`in e?e.contains(s):e.compareDocumentPosition?!!(e.compareDocumentPosition(s)&16):!1:!1}function Dg(e){e=e!=null&&e.ownerDocument!=null&&e.ownerDocument.defaultView!=null?e.ownerDocument.defaultView:window;for(var s=jl(e.document);s instanceof e.HTMLIFrameElement;){try{var a=typeof s.contentWindow.location.href==`string`}catch{a=!1}if(a)e=s.contentWindow;else break;s=jl(e.document)}return s}function ku(e){var s=e&&e.nodeName&&e.nodeName.toLowerCase();return s&&(s===`input`&&(e.type===`text`||e.type===`search`||e.type===`tel`||e.type===`url`||e.type===`password`)||s===`textarea`||e.contentEditable===`true`)}var $E=Qn&&`documentMode`in document&&11>=document.documentMode,Gi=null,Uu=null,ha=null,zu=!1;function Mg(e,s,a){var c=a.window===a?a.document:a.nodeType===9?a:a.ownerDocument;zu||Gi==null||Gi!==jl(c)||(c=Gi,`selectionStart`in c&&ku(c)?c={start:c.selectionStart,end:c.selectionEnd}:(c=(c.ownerDocument&&c.ownerDocument.defaultView||window).getSelection(),c={anchorNode:c.anchorNode,anchorOffset:c.anchorOffset,focusNode:c.focusNode,focusOffset:c.focusOffset}),ha&&fa(ha,c)||(ha=c,c=ko(Uu,`onSelect`),0>=S,f-=S,Mn=1<<32-Qe(s)+f|a<vt?(_t=lt,lt=null):_t=lt.sibling;var kt=N(D,lt,U[vt],V);if(kt===null){lt===null&&(lt=_t);break}e&<&&kt.alternate===null&&s(D,lt),R=h(kt,R,vt),Mt===null?ct=kt:Mt.sibling=kt,Mt=kt,lt=_t}if(vt===U.length)return a(D,lt),At&&Jn(D,vt),ct;if(lt===null){for(;vtvt?(_t=lt,lt=null):_t=lt.sibling;var Vs=N(D,lt,kt.value,V);if(Vs===null){lt===null&&(lt=_t);break}e&<&&Vs.alternate===null&&s(D,lt),R=h(Vs,R,vt),Mt===null?ct=Vs:Mt.sibling=Vs,Mt=Vs,lt=_t}if(kt.done)return a(D,lt),At&&Jn(D,vt),ct;if(lt===null){for(;!kt.done;vt++,kt=U.next())kt=$(D,kt.value,V),kt!==null&&(R=h(kt,R,vt),Mt===null?ct=kt:Mt.sibling=kt,Mt=kt);return At&&Jn(D,vt),ct}for(lt=c(lt);!kt.done;vt++,kt=U.next())kt=L(lt,D,vt,kt.value,V),kt!==null&&(e&&kt.alternate!==null&<.delete(kt.key===null?vt:kt.key),R=h(kt,R,vt),Mt===null?ct=kt:Mt.sibling=kt,Mt=kt);return e&<.forEach(function(uC){return s(D,uC)}),At&&Jn(D,vt),ct}function qt(D,R,U,V){if(typeof U==`object`&&U!==null&&U.type===E&&U.key===null&&(U=U.props.children),typeof U==`object`&&U!==null){switch(U.$$typeof){case w:t:{for(var ct=U.key;R!==null;){if(R.key===ct){if(ct=U.type,ct===E){if(R.tag===7){a(D,R.sibling),V=f(R,U.props.children),V.return=D,D=V;break t}}else if(R.elementType===ct||typeof ct==`object`&&ct!==null&&ct.$$typeof===W&&hi(ct)===R.type){a(D,R.sibling),V=f(R,U.props),Sa(V,U),V.return=D,D=V;break t}a(D,R);break}else s(D,R);R=R.sibling}U.type===E?(V=li(U.props.children,D.mode,V,U.key),V.return=D,D=V):(V=Ql(U.type,U.key,U.props,null,D.mode,V),Sa(V,U),V.return=D,D=V)}return S(D);case b:t:{for(ct=U.key;R!==null;){if(R.key===ct)if(R.tag===4&&R.stateNode.containerInfo===U.containerInfo&&R.stateNode.implementation===U.implementation){a(D,R.sibling),V=f(R,U.children||[]),V.return=D,D=V;break t}else{a(D,R);break}else s(D,R);R=R.sibling}V=qu(U,D.mode,V),V.return=D,D=V}return S(D);case W:return U=hi(U),qt(D,R,U,V)}if(dt(U))return rt(D,R,U,V);if(nt(U)){if(ct=nt(U),typeof ct!=`function`)throw Error(r(150));return U=ct.call(U),ut(D,R,U,V)}if(typeof U.then==`function`)return qt(D,R,eo(U),V);if(U.$$typeof===A)return qt(D,R,Zl(D,U),V);no(D,U)}return typeof U==`string`&&U!==``||typeof U==`number`||typeof U==`bigint`?(U=``+U,R!==null&&R.tag===6?(a(D,R.sibling),V=f(R,U),V.return=D,D=V):(a(D,R),V=Hu(U,D.mode,V),V.return=D,D=V),S(D)):a(D,R)}return function(D,R,U,V){try{ma=0;var ct=qt(D,R,U,V);return nr=null,ct}catch(lt){if(lt===er||lt===Pl)throw lt;var Mt=Je(29,lt,null,D.mode);return Mt.lanes=V,Mt.return=D,Mt}}}var pi=ty(!0),ey=ty(!1),Ts=!1;function Pu(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function tf(e,s){e=e.updateQueue,s.updateQueue===e&&(s.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,callbacks:null})}function As(e){return{lane:e,tag:0,payload:null,callback:null,next:null}}function Os(e,s,a){var c=e.updateQueue;if(c===null)return null;if(c=c.shared,(zt&2)!==0){var f=c.pending;return f===null?s.next=s:(s.next=f.next,f.next=s),c.pending=s,s=Fl(e),Lg(e,null,a),s}return Yl(e,c,s,a),Fl(e)}function va(e,s,a){if(s=s.updateQueue,s!==null&&(s=s.shared,(a&4194048)!==0)){var c=s.lanes;c&=e.pendingLanes,a|=c,s.lanes=a,Yp(e,a)}}function ef(e,s){var a=e.updateQueue,c=e.alternate;if(c!==null&&(c=c.updateQueue,a===c)){var f=null,h=null;if(a=a.firstBaseUpdate,a!==null){do{var S={lane:a.lane,tag:a.tag,payload:a.payload,callback:null,next:null};h===null?f=h=S:h=h.next=S,a=a.next}while(a!==null);h===null?f=h=s:h=h.next=s}else f=h=s;a={baseState:c.baseState,firstBaseUpdate:f,lastBaseUpdate:h,shared:c.shared,callbacks:c.callbacks},e.updateQueue=a;return}e=a.lastBaseUpdate,e===null?a.firstBaseUpdate=s:e.next=s,a.lastBaseUpdate=s}var nf=!1;function ba(){if(nf){var e=tr;if(e!==null)throw e}}function wa(e,s,a,c){nf=!1;var f=e.updateQueue;Ts=!1;var h=f.firstBaseUpdate,S=f.lastBaseUpdate,C=f.shared.pending;if(C!==null){f.shared.pending=null;var x=C,z=x.next;x.next=null,S===null?h=z:S.next=z,S=x;var H=e.alternate;H!==null&&(H=H.updateQueue,C=H.lastBaseUpdate,C!==S&&(C===null?H.firstBaseUpdate=z:C.next=z,H.lastBaseUpdate=x))}if(h!==null){var $=f.baseState;S=0,H=z=x=null,C=h;do{var N=C.lane&-536870913,L=N!==C.lane;if(L?(xt&N)===N:(c&N)===N){N!==0&&N===Pi&&(nf=!0),H!==null&&(H=H.next={lane:0,tag:C.tag,payload:C.payload,callback:null,next:null});t:{var rt=e,ut=C;N=s;var qt=a;switch(ut.tag){case 1:if(rt=ut.payload,typeof rt==`function`){$=rt.call(qt,$,N);break t}$=rt;break t;case 3:rt.flags=rt.flags&-65537|128;case 0:if(rt=ut.payload,N=typeof rt==`function`?rt.call(qt,$,N):rt,N==null)break t;$=m({},$,N);break t;case 2:Ts=!0}}N=C.callback,N!==null&&(e.flags|=64,L&&(e.flags|=8192),L=f.callbacks,L===null?f.callbacks=[N]:L.push(N))}else L={lane:N,tag:C.tag,payload:C.payload,callback:C.callback,next:null},H===null?(z=H=L,x=$):H=H.next=L,S|=N;if(C=C.next,C===null){if(C=f.shared.pending,C===null)break;L=C,C=L.next,L.next=null,f.lastBaseUpdate=L,f.shared.pending=null}}while(!0);H===null&&(x=$),f.baseState=x,f.firstBaseUpdate=z,f.lastBaseUpdate=H,h===null&&(f.shared.lanes=0),Us|=S,e.lanes=S,e.memoizedState=$}}function ny(e,s){if(typeof e!=`function`)throw Error(r(191,e));e.call(s)}function sy(e,s){var a=e.callbacks;if(a!==null)for(e.callbacks=null,e=0;eh?h:8;var S=k.T,C={};k.T=C,Ef(e,!1,s,a);try{var x=f(),z=k.S;if(z!==null&&z(C,x),x!==null&&typeof x==`object`&&typeof x.then==`function`){var H=PE(x,c);xa(e,s,H,en(e))}else xa(e,s,c,en(e))}catch($){xa(e,s,{then:function(){},status:`rejected`,reason:$},en())}finally{I.p=h,S!==null&&C.types!==null&&(S.types=C.types),k.T=S}}function r1(){}function bf(e,s,a,c){if(e.tag!==5)throw Error(r(476));var f=Ny(e).queue;zy(e,f,s,Z,a===null?r1:function(){return jy(e),a(c)})}function Ny(e){var s=e.memoizedState;if(s!==null)return s;s={memoizedState:Z,baseState:Z,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:ts,lastRenderedState:Z},next:null};var a={};return s.next={memoizedState:a,baseState:a,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:ts,lastRenderedState:a},next:null},e.memoizedState=s,e=e.alternate,e!==null&&(e.memoizedState=s),s}function jy(e){var s=Ny(e);s.next===null&&(s=e.alternate.memoizedState),xa(e,s.next.queue,{},en())}function wf(){return Ee(qa)}function By(){return te().memoizedState}function Ly(){return te().memoizedState}function a1(e){for(var s=e.return;s!==null;){switch(s.tag){case 24:case 3:var a=en();e=As(a);var c=Os(s,e,a);c!==null&&(Ke(c,s,a),va(c,s,a)),s={cache:Xu()},e.payload=s;return}s=s.return}}function l1(e,s,a){var c=en();a={lane:c,revertLane:0,gesture:null,action:a,hasEagerState:!1,eagerState:null,next:null},ho(e)?Hy(s,a):(a=Lu(e,s,a,c),a!==null&&(Ke(a,e,c),qy(a,s,c)))}function Iy(e,s,a){var c=en();xa(e,s,a,c)}function xa(e,s,a,c){var f={lane:c,revertLane:0,gesture:null,action:a,hasEagerState:!1,eagerState:null,next:null};if(ho(e))Hy(s,f);else{var h=e.alternate;if(e.lanes===0&&(h===null||h.lanes===0)&&(h=s.lastRenderedReducer,h!==null))try{var S=s.lastRenderedState,C=h(S,a);if(f.hasEagerState=!0,f.eagerState=C,Xe(C,S))return Yl(e,s,f,0),Kt===null&&Gl(),!1}catch{}if(a=Lu(e,s,f,c),a!==null)return Ke(a,e,c),qy(a,s,c),!0}return!1}function Ef(e,s,a,c){if(c={lane:2,revertLane:th(),gesture:null,action:c,hasEagerState:!1,eagerState:null,next:null},ho(e)){if(s)throw Error(r(479))}else s=Lu(e,a,c,2),s!==null&&Ke(s,e,2)}function ho(e){var s=e.alternate;return e===St||s!==null&&s===St}function Hy(e,s){ir=ro=!0;var a=e.pending;a===null?s.next=s:(s.next=a.next,a.next=s),e.pending=s}function qy(e,s,a){if((a&4194048)!==0){var c=s.lanes;c&=e.pendingLanes,a|=c,s.lanes=a,Yp(e,a)}}var _a={readContext:Ee,use:oo,useCallback:Xt,useContext:Xt,useEffect:Xt,useImperativeHandle:Xt,useLayoutEffect:Xt,useInsertionEffect:Xt,useMemo:Xt,useReducer:Xt,useRef:Xt,useState:Xt,useDebugValue:Xt,useDeferredValue:Xt,useTransition:Xt,useSyncExternalStore:Xt,useId:Xt,useHostTransitionStatus:Xt,useFormState:Xt,useActionState:Xt,useOptimistic:Xt,useMemoCache:Xt,useCacheRefresh:Xt};_a.useEffectEvent=Xt;var Ky={readContext:Ee,use:oo,useCallback:function(e,s){return Me().memoizedState=[e,s===void 0?null:s],e},useContext:Ee,useEffect:_y,useImperativeHandle:function(e,s,a){a=a!=null?a.concat([e]):null,uo(4194308,4,Ry.bind(null,s,e),a)},useLayoutEffect:function(e,s){return uo(4194308,4,e,s)},useInsertionEffect:function(e,s){uo(4,2,e,s)},useMemo:function(e,s){var a=Me();s=s===void 0?null:s;var c=e();if(gi){vs(!0);try{e()}finally{vs(!1)}}return a.memoizedState=[c,s],c},useReducer:function(e,s,a){var c=Me();if(a!==void 0){var f=a(s);if(gi){vs(!0);try{a(s)}finally{vs(!1)}}}else f=s;return c.memoizedState=c.baseState=f,e={pending:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:f},c.queue=e,e=e.dispatch=l1.bind(null,St,e),[c.memoizedState,e]},useRef:function(e){var s=Me();return e={current:e},s.memoizedState=e},useState:function(e){e=gf(e);var s=e.queue,a=Iy.bind(null,St,s);return s.dispatch=a,[e.memoizedState,a]},useDebugValue:Sf,useDeferredValue:function(e,s){var a=Me();return vf(a,e,s)},useTransition:function(){var e=gf(!1);return e=zy.bind(null,St,e.queue,!0,!1),Me().memoizedState=e,[!1,e]},useSyncExternalStore:function(e,s,a){var c=St,f=Me();if(At){if(a===void 0)throw Error(r(407));a=a()}else{if(a=s(),Kt===null)throw Error(r(349));(xt&127)!==0||cy(c,s,a)}f.memoizedState=a;var h={value:a,getSnapshot:s};return f.queue=h,_y(fy.bind(null,c,h,e),[e]),c.flags|=2048,ar(9,{destroy:void 0},uy.bind(null,c,h,a,s),null),a},useId:function(){var e=Me(),s=Kt.identifierPrefix;if(At){var a=kn,c=Mn;a=(c&~(1<<32-Qe(c)-1)).toString(32)+a,s=`_`+s+`R_`+a,a=ao++,0<\/script>`,h=h.removeChild(h.firstChild);break;case`select`:h=typeof c.is==`string`?S.createElement(`select`,{is:c.is}):S.createElement(`select`),c.multiple?h.multiple=!0:c.size&&(h.size=c.size);break;default:h=typeof c.is==`string`?S.createElement(f,{is:c.is}):S.createElement(f)}}h[be]=s,h[je]=c;t:for(S=s.child;S!==null;){if(S.tag===5||S.tag===6)h.appendChild(S.stateNode);else if(S.tag!==4&&S.tag!==27&&S.child!==null){S.child.return=S,S=S.child;continue}if(S===s)break t;for(;S.sibling===null;){if(S.return===null||S.return===s)break t;S=S.return}S.sibling.return=S.return,S=S.sibling}s.stateNode=h;t:switch(xe(h,f,c),f){case`button`:case`input`:case`select`:case`textarea`:c=!!c.autoFocus;break t;case`img`:c=!0;break t;default:c=!1}c&&ns(s)}}return Yt(s),jf(s,s.type,e===null?null:e.memoizedProps,s.pendingProps,a),null;case 6:if(e&&s.stateNode!=null)e.memoizedProps!==c&&ns(s);else{if(typeof c!=`string`&&s.stateNode===null)throw Error(r(166));if(e=st.current,Zi(s)){if(e=s.stateNode,a=s.memoizedProps,c=null,f=we,f!==null)switch(f.tag){case 27:case 5:c=f.memoizedProps}e[be]=s,e=!!(e.nodeValue===a||c!==null&&c.suppressHydrationWarning===!0||l0(e.nodeValue,a)),e||xs(s,!0)}else e=Uo(e).createTextNode(c),e[be]=s,s.stateNode=e}return Yt(s),null;case 31:if(a=s.memoizedState,e===null||e.memoizedState!==null){if(c=Zi(s),a!==null){if(e===null){if(!c)throw Error(r(318));if(e=s.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(r(557));e[be]=s}else oi(),(s.flags&128)===0&&(s.memoizedState=null),s.flags|=4;Yt(s),e=!1}else a=Gu(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=a),e=!0;if(!e)return s.flags&256?(We(s),s):(We(s),null);if((s.flags&128)!==0)throw Error(r(558))}return Yt(s),null;case 13:if(c=s.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(f=Zi(s),c!==null&&c.dehydrated!==null){if(e===null){if(!f)throw Error(r(318));if(f=s.memoizedState,f=f!==null?f.dehydrated:null,!f)throw Error(r(317));f[be]=s}else oi(),(s.flags&128)===0&&(s.memoizedState=null),s.flags|=4;Yt(s),f=!1}else f=Gu(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=f),f=!0;if(!f)return s.flags&256?(We(s),s):(We(s),null)}return We(s),(s.flags&128)!==0?(s.lanes=a,s):(a=c!==null,e=e!==null&&e.memoizedState!==null,a&&(c=s.child,f=null,c.alternate!==null&&c.alternate.memoizedState!==null&&c.alternate.memoizedState.cachePool!==null&&(f=c.alternate.memoizedState.cachePool.pool),h=null,c.memoizedState!==null&&c.memoizedState.cachePool!==null&&(h=c.memoizedState.cachePool.pool),h!==f&&(c.flags|=2048)),a!==e&&a&&(s.child.flags|=8192),So(s,s.updateQueue),Yt(s),null);case 4:return wt(),e===null&&ih(s.stateNode.containerInfo),Yt(s),null;case 10:return Wn(s.type),Yt(s),null;case 19:if(B(Pt),c=s.memoizedState,c===null)return Yt(s),null;if(f=(s.flags&128)!==0,h=c.rendering,h===null)if(f)Aa(c,!1);else{if(Jt!==0||e!==null&&(e.flags&128)!==0)for(e=s.child;e!==null;){if(h=io(e),h!==null){for(s.flags|=128,Aa(c,!1),e=h.updateQueue,s.updateQueue=e,So(s,e),s.subtreeFlags=0,e=a,a=s.child;a!==null;)Ig(a,e),a=a.sibling;return Y(Pt,Pt.current&1|2),At&&Jn(s,c.treeForkCount),s.child}e=e.sibling}c.tail!==null&&ht()>Co&&(s.flags|=128,f=!0,Aa(c,!1),s.lanes=4194304)}else{if(!f)if(e=io(h),e!==null){if(s.flags|=128,f=!0,e=e.updateQueue,s.updateQueue=e,So(s,e),Aa(c,!0),c.tail===null&&c.tailMode===`hidden`&&!h.alternate&&!At)return Yt(s),null}else 2*ht()-c.renderingStartTime>Co&&a!==536870912&&(s.flags|=128,f=!0,Aa(c,!1),s.lanes=4194304);c.isBackwards?(h.sibling=s.child,s.child=h):(e=c.last,e!==null?e.sibling=h:s.child=h,c.last=h)}return c.tail!==null?(e=c.tail,c.rendering=e,c.tail=e.sibling,c.renderingStartTime=ht(),e.sibling=null,a=Pt.current,Y(Pt,f?a&1|2:a&1),At&&Jn(s,c.treeForkCount),e):(Yt(s),null);case 22:case 23:return We(s),rf(),c=s.memoizedState!==null,e!==null?e.memoizedState!==null!==c&&(s.flags|=8192):c&&(s.flags|=8192),c?(a&536870912)!==0&&(s.flags&128)===0&&(Yt(s),s.subtreeFlags&6&&(s.flags|=8192)):Yt(s),a=s.updateQueue,a!==null&&So(s,a.retryQueue),a=null,e!==null&&e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(a=e.memoizedState.cachePool.pool),c=null,s.memoizedState!==null&&s.memoizedState.cachePool!==null&&(c=s.memoizedState.cachePool.pool),c!==a&&(s.flags|=2048),e!==null&&B(fi),null;case 24:return a=null,e!==null&&(a=e.memoizedState.cache),s.memoizedState.cache!==a&&(s.flags|=2048),Wn(se),Yt(s),null;case 25:return null;case 30:return null}throw Error(r(156,s.tag))}function h1(e,s){switch(Vu(s),s.tag){case 1:return e=s.flags,e&65536?(s.flags=e&-65537|128,s):null;case 3:return Wn(se),wt(),e=s.flags,(e&65536)!==0&&(e&128)===0?(s.flags=e&-65537|128,s):null;case 26:case 27:case 5:return $e(s),null;case 31:if(s.memoizedState!==null){if(We(s),s.alternate===null)throw Error(r(340));oi()}return e=s.flags,e&65536?(s.flags=e&-65537|128,s):null;case 13:if(We(s),e=s.memoizedState,e!==null&&e.dehydrated!==null){if(s.alternate===null)throw Error(r(340));oi()}return e=s.flags,e&65536?(s.flags=e&-65537|128,s):null;case 19:return B(Pt),null;case 4:return wt(),null;case 10:return Wn(s.type),null;case 22:case 23:return We(s),rf(),e!==null&&B(fi),e=s.flags,e&65536?(s.flags=e&-65537|128,s):null;case 24:return Wn(se),null;case 25:return null;default:return null}}function hm(e,s){switch(Vu(s),s.tag){case 3:Wn(se),wt();break;case 26:case 27:case 5:$e(s);break;case 4:wt();break;case 31:s.memoizedState!==null&&We(s);break;case 13:We(s);break;case 19:B(Pt);break;case 10:Wn(s.type);break;case 22:case 23:We(s),rf(),e!==null&&B(fi);break;case 24:Wn(se)}}function Oa(e,s){try{var a=s.updateQueue,c=a!==null?a.lastEffect:null;if(c!==null){var f=c.next;a=f;do{if((a.tag&e)===e){c=void 0;var h=a.create,S=a.inst;c=h(),S.destroy=c}a=a.next}while(a!==f)}}catch(C){Bt(s,s.return,C)}}function Ms(e,s,a){try{var c=s.updateQueue,f=c!==null?c.lastEffect:null;if(f!==null){var h=f.next;c=h;do{if((c.tag&e)===e){var S=c.inst,C=S.destroy;if(C!==void 0){S.destroy=void 0,f=s;var x=a,z=C;try{z()}catch(H){Bt(f,x,H)}}}c=c.next}while(c!==h)}}catch(H){Bt(s,s.return,H)}}function dm(e){var s=e.updateQueue;if(s!==null){var a=e.stateNode;try{sy(s,a)}catch(c){Bt(e,e.return,c)}}}function pm(e,s,a){a.props=yi(e.type,e.memoizedProps),a.state=e.memoizedState;try{a.componentWillUnmount()}catch(c){Bt(e,s,c)}}function Ra(e,s){try{var a=e.ref;if(a!==null){switch(e.tag){case 26:case 27:case 5:var c=e.stateNode;break;case 30:c=e.stateNode;break;default:c=e.stateNode}typeof a==`function`?e.refCleanup=a(c):a.current=c}}catch(f){Bt(e,s,f)}}function Un(e,s){var a=e.ref,c=e.refCleanup;if(a!==null)if(typeof c==`function`)try{c()}catch(f){Bt(e,s,f)}finally{e.refCleanup=null,e=e.alternate,e!=null&&(e.refCleanup=null)}else if(typeof a==`function`)try{a(null)}catch(f){Bt(e,s,f)}else a.current=null}function gm(e){var s=e.type,a=e.memoizedProps,c=e.stateNode;try{t:switch(s){case`button`:case`input`:case`select`:case`textarea`:a.autoFocus&&c.focus();break t;case`img`:a.src?c.src=a.src:a.srcSet&&(c.srcset=a.srcSet)}}catch(f){Bt(e,e.return,f)}}function Bf(e,s,a){try{var c=e.stateNode;z1(c,e.type,a,s),c[je]=s}catch(f){Bt(e,e.return,f)}}function ym(e){return e.tag===5||e.tag===3||e.tag===26||e.tag===27&&Ls(e.type)||e.tag===4}function Lf(e){t:for(;;){for(;e.sibling===null;){if(e.return===null||ym(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.tag===27&&Ls(e.type)||e.flags&2||e.child===null||e.tag===4)continue t;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function If(e,s,a){var c=e.tag;if(c===5||c===6)e=e.stateNode,s?(a.nodeType===9?a.body:a.nodeName===`HTML`?a.ownerDocument.body:a).insertBefore(e,s):(s=a.nodeType===9?a.body:a.nodeName===`HTML`?a.ownerDocument.body:a,s.appendChild(e),a=a._reactRootContainer,a!=null||s.onclick!==null||(s.onclick=Fn));else if(c!==4&&(c===27&&Ls(e.type)&&(a=e.stateNode,s=null),e=e.child,e!==null))for(If(e,s,a),e=e.sibling;e!==null;)If(e,s,a),e=e.sibling}function vo(e,s,a){var c=e.tag;if(c===5||c===6)e=e.stateNode,s?a.insertBefore(e,s):a.appendChild(e);else if(c!==4&&(c===27&&Ls(e.type)&&(a=e.stateNode),e=e.child,e!==null))for(vo(e,s,a),e=e.sibling;e!==null;)vo(e,s,a),e=e.sibling}function mm(e){var s=e.stateNode,a=e.memoizedProps;try{for(var c=e.type,f=s.attributes;f.length;)s.removeAttributeNode(f[0]);xe(s,c,a),s[be]=e,s[je]=a}catch(h){Bt(e,e.return,h)}}var ss=!1,ae=!1,Hf=!1,Sm=typeof WeakSet==`function`?WeakSet:Set,pe=null;function d1(e,s){if(e=e.containerInfo,lh=Ho,e=Dg(e),ku(e)){if(`selectionStart`in e)var a={start:e.selectionStart,end:e.selectionEnd};else t:{a=(a=e.ownerDocument)&&a.defaultView||window;var c=a.getSelection&&a.getSelection();if(c&&c.rangeCount!==0){a=c.anchorNode;var f=c.anchorOffset,h=c.focusNode;c=c.focusOffset;try{a.nodeType,h.nodeType}catch{a=null;break t}var S=0,C=-1,x=-1,z=0,H=0,$=e,N=null;e:for(;;){for(var L;$!==a||f!==0&&$.nodeType!==3||(C=S+f),$!==h||c!==0&&$.nodeType!==3||(x=S+c),$.nodeType===3&&(S+=$.nodeValue.length),(L=$.firstChild)!==null;)N=$,$=L;for(;;){if($===e)break e;if(N===a&&++z===f&&(C=S),N===h&&++H===c&&(x=S),(L=$.nextSibling)!==null)break;$=N,N=$.parentNode}$=L}a=C===-1||x===-1?null:{start:C,end:x}}else a=null}a=a||{start:0,end:0}}else a=null;for(oh={focusedElem:e,selectionRange:a},Ho=!1,pe=s;pe!==null;)if(s=pe,e=s.child,(s.subtreeFlags&1028)!==0&&e!==null)e.return=s,pe=e;else for(;pe!==null;){switch(s=pe,h=s.alternate,e=s.flags,s.tag){case 0:if((e&4)!==0&&(e=s.updateQueue,e=e!==null?e.events:null,e!==null))for(a=0;a title`))),xe(h,c,a),h[be]=e,de(h),c=h;break t;case`link`:var S=x0(`link`,`href`,f).get(c+(a.href||``));if(S){for(var C=0;Cqt&&(S=qt,qt=ut,ut=S);var D=Og(C,ut),R=Og(C,qt);if(D&&R&&(L.rangeCount!==1||L.anchorNode!==D.node||L.anchorOffset!==D.offset||L.focusNode!==R.node||L.focusOffset!==R.offset)){var U=$.createRange();U.setStart(D.node,D.offset),L.removeAllRanges(),ut>qt?(L.addRange(U),L.extend(R.node,R.offset)):(U.setEnd(R.node,R.offset),L.addRange(U))}}}}for($=[],L=C;L=L.parentNode;)L.nodeType===1&&$.push({element:L,left:L.scrollLeft,top:L.scrollTop});for(typeof C.focus==`function`&&C.focus(),C=0;C<$.length;C++){var V=$[C];V.element.scrollLeft=V.left,V.element.scrollTop=V.top}}Ho=!!lh,oh=lh=null}finally{zt=f,I.p=c,k.T=a}}e.current=s,ce=2}}function Gm(){if(ce===2){ce=0;var e=Ns,s=fr,a=(s.flags&8772)!==0;if((s.subtreeFlags&8772)!==0||a){a=k.T,k.T=null;var c=I.p;I.p=2;var f=zt;zt|=4;try{vm(e,s.alternate,s)}finally{zt=f,I.p=c,k.T=a}}ce=3}}function Ym(){if(ce===4||ce===3){ce=0,pt();var e=Ns,s=fr,a=os,c=km;(s.subtreeFlags&10256)!==0||(s.flags&10256)!==0?ce=5:(ce=0,fr=Ns=null,Fm(e,e.pendingLanes));var f=e.pendingLanes;if(f===0&&(zs=null),du(a),s=s.stateNode,Fe&&typeof Fe.onCommitFiberRoot==`function`)try{Fe.onCommitFiberRoot(Pr,s,void 0,(s.current.flags&128)===128)}catch{}if(c!==null){s=k.T,f=I.p,I.p=2,k.T=null;try{for(var h=e.onRecoverableError,S=0;Sa?32:a,k.T=null,a=Ff,Ff=null;var h=Ns,S=os;if(ce=0,fr=Ns=null,os=0,(zt&6)!==0)throw Error(r(331));var C=zt;if(zt|=4,Rm(h.current),Tm(h,h.current,S,a),zt=C,Na(0,!1),Fe&&typeof Fe.onPostCommitFiberRoot==`function`)try{Fe.onPostCommitFiberRoot(Pr,h)}catch{}return!0}finally{I.p=f,k.T=c,Fm(e,s)}}function Xm(e,s,a){s=un(a,s),s=Tf(e.stateNode,s,2),e=Os(e,s,2),e!==null&&(ea(e,2),zn(e))}function Bt(e,s,a){if(e.tag===3)Xm(e,e,a);else for(;s!==null;){if(s.tag===3){Xm(s,e,a);break}else if(s.tag===1){var c=s.stateNode;if(typeof s.type.getDerivedStateFromError==`function`||typeof c.componentDidCatch==`function`&&(zs===null||!zs.has(c))){e=un(a,e),a=Jy(2),c=Os(s,a,2),c!==null&&(Zy(a,c,s,e),ea(c,2),zn(c));break}}s=s.return}}function Zf(e,s,a){var c=e.pingCache;if(c===null){c=e.pingCache=new y1;var f=new Set;c.set(s,f)}else f=c.get(s),f===void 0&&(f=new Set,c.set(s,f));f.has(a)||(Vf=!0,f.add(a),e=w1.bind(null,e,s,a),s.then(e,e))}function w1(e,s,a){var c=e.pingCache;c!==null&&c.delete(s),e.pingedLanes|=e.suspendedLanes&a,e.warmLanes&=~a,Kt===e&&(xt&a)===a&&(Jt===4||Jt===3&&(xt&62914560)===xt&&300>ht()-Eo?(zt&2)===0&&hr(e,0):$f|=a,ur===xt&&(ur=0)),zn(e)}function Jm(e,s){s===0&&(s=$p()),e=ai(e,s),e!==null&&(ea(e,s),zn(e))}function E1(e){var s=e.memoizedState,a=0;s!==null&&(a=s.retryLane),Jm(e,a)}function C1(e,s){var a=0;switch(e.tag){case 31:case 13:var c=e.stateNode,f=e.memoizedState;f!==null&&(a=f.retryLane);break;case 19:c=e.stateNode;break;case 22:c=e.stateNode._retryCache;break;default:throw Error(r(314))}c!==null&&c.delete(s),Jm(e,a)}function x1(e,s){return tt(e,s)}var Ro=null,pr=null,Wf=!1,Do=!1,Pf=!1,Bs=0;function zn(e){e!==pr&&e.next===null&&(pr===null?Ro=pr=e:pr=pr.next=e),Do=!0,Wf||(Wf=!0,T1())}function Na(e,s){if(!Pf&&Do){Pf=!0;do for(var a=!1,c=Ro;c!==null;){if(e!==0){var f=c.pendingLanes;if(f===0)var h=0;else{var S=c.suspendedLanes,C=c.pingedLanes;h=(1<<31-Qe(42|e)+1)-1,h&=f&~(S&~C),h=h&201326741?h&201326741|1:h?h|2:0}h!==0&&(a=!0,t0(c,h))}else h=xt,h=Ul(c,c===Kt?h:0,c.cancelPendingCommit!==null||c.timeoutHandle!==-1),(h&3)===0||ta(c,h)||(a=!0,t0(c,h));c=c.next}while(a);Pf=!1}}function _1(){Zm()}function Zm(){Do=Wf=!1;var e=0;Bs!==0&&j1()&&(e=Bs);for(var s=ht(),a=null,c=Ro;c!==null;){var f=c.next,h=Wm(c,s);h===0?(c.next=null,a===null?Ro=f:a.next=f,f===null&&(pr=a)):(a=c,(e!==0||(h&3)!==0)&&(Do=!0)),c=f}ce!==0&&ce!==5||Na(e),Bs!==0&&(Bs=0)}function Wm(e,s){for(var a=e.suspendedLanes,c=e.pingedLanes,f=e.expirationTimes,h=e.pendingLanes&-62914561;0C)break;var H=x.transferSize,$=x.initiatorType;H&&o0($)&&(x=x.responseEnd,S+=H*(x`u`?null:document;function b0(e,s,a){var c=gr;if(c&&typeof s==`string`&&s){var f=on(s);f=`link[rel="`+e+`"][href="`+f+`"]`,typeof a==`string`&&(f+=`[crossorigin="`+a+`"]`),v0.has(f)||(v0.add(f),e={rel:e,crossOrigin:a,href:s},c.querySelector(f)===null&&(s=c.createElement(`link`),xe(s,`link`,e),de(s),c.head.appendChild(s)))}}function G1(e){cs.D(e),b0(`dns-prefetch`,e,null)}function Y1(e,s){cs.C(e,s),b0(`preconnect`,e,s)}function F1(e,s,a){cs.L(e,s,a);var c=gr;if(c&&e&&s){var f=`link[rel="preload"][as="`+on(s)+`"]`;s===`image`&&a&&a.imageSrcSet?(f+=`[imagesrcset="`+on(a.imageSrcSet)+`"]`,typeof a.imageSizes==`string`&&(f+=`[imagesizes="`+on(a.imageSizes)+`"]`)):f+=`[href="`+on(e)+`"]`;var h=f;switch(s){case`style`:h=yr(e);break;case`script`:h=mr(e)}yn.has(h)||(e=m({rel:`preload`,href:s===`image`&&a&&a.imageSrcSet?void 0:e,as:s},a),yn.set(h,e),c.querySelector(f)!==null||s===`style`&&c.querySelector(Ia(h))||s===`script`&&c.querySelector(Ha(h))||(s=c.createElement(`link`),xe(s,`link`,e),de(s),c.head.appendChild(s)))}}function Q1(e,s){cs.m(e,s);var a=gr;if(a&&e){var c=s&&typeof s.as==`string`?s.as:`script`,f=`link[rel="modulepreload"][as="`+on(c)+`"][href="`+on(e)+`"]`,h=f;switch(c){case`audioworklet`:case`paintworklet`:case`serviceworker`:case`sharedworker`:case`worker`:case`script`:h=mr(e)}if(!yn.has(h)&&(e=m({rel:`modulepreload`,href:e},s),yn.set(h,e),a.querySelector(f)===null)){switch(c){case`audioworklet`:case`paintworklet`:case`serviceworker`:case`sharedworker`:case`worker`:case`script`:if(a.querySelector(Ha(h)))return}c=a.createElement(`link`),xe(c,`link`,e),de(c),a.head.appendChild(c)}}}function X1(e,s,a){cs.S(e,s,a);var c=gr;if(c&&e){var f=Li(c).hoistableStyles,h=yr(e);s=s||`default`;var S=f.get(h);if(!S){var C={loading:0,preload:null};if(S=c.querySelector(Ia(h)))C.loading=5;else{e=m({rel:`stylesheet`,href:e,"data-precedence":s},a),(a=yn.get(h))&&gh(e,a);var x=S=c.createElement(`link`);de(x),xe(x,`link`,e),x._p=new Promise(function(z,H){x.onload=z,x.onerror=H}),x.addEventListener(`load`,function(){C.loading|=1}),x.addEventListener(`error`,function(){C.loading|=2}),C.loading|=4,No(S,s,c)}S={type:`stylesheet`,instance:S,count:1,state:C},f.set(h,S)}}}function J1(e,s){cs.X(e,s);var a=gr;if(a&&e){var c=Li(a).hoistableScripts,f=mr(e),h=c.get(f);h||(h=a.querySelector(Ha(f)),h||(e=m({src:e,async:!0},s),(s=yn.get(f))&&yh(e,s),h=a.createElement(`script`),de(h),xe(h,`link`,e),a.head.appendChild(h)),h={type:`script`,instance:h,count:1,state:null},c.set(f,h))}}function Z1(e,s){cs.M(e,s);var a=gr;if(a&&e){var c=Li(a).hoistableScripts,f=mr(e),h=c.get(f);h||(h=a.querySelector(Ha(f)),h||(e=m({src:e,async:!0,type:`module`},s),(s=yn.get(f))&&yh(e,s),h=a.createElement(`script`),de(h),xe(h,`link`,e),a.head.appendChild(h)),h={type:`script`,instance:h,count:1,state:null},c.set(f,h))}}function w0(e,s,a,c){var f=(f=st.current)?zo(f):null;if(!f)throw Error(r(446));switch(e){case`meta`:case`title`:return null;case`style`:return typeof a.precedence==`string`&&typeof a.href==`string`?(s=yr(a.href),a=Li(f).hoistableStyles,c=a.get(s),c||(c={type:`style`,instance:null,count:0,state:null},a.set(s,c)),c):{type:`void`,instance:null,count:0,state:null};case`link`:if(a.rel===`stylesheet`&&typeof a.href==`string`&&typeof a.precedence==`string`){e=yr(a.href);var h=Li(f).hoistableStyles,S=h.get(e);if(S||(f=f.ownerDocument||f,S={type:`stylesheet`,instance:null,count:0,state:{loading:0,preload:null}},h.set(e,S),(h=f.querySelector(Ia(e)))&&!h._p&&(S.instance=h,S.state.loading=5),yn.has(e)||(a={rel:`preload`,as:`style`,href:a.href,crossOrigin:a.crossOrigin,integrity:a.integrity,media:a.media,hrefLang:a.hrefLang,referrerPolicy:a.referrerPolicy},yn.set(e,a),h||W1(f,e,a,S.state))),s&&c===null)throw Error(r(528,``));return S}if(s&&c!==null)throw Error(r(529,``));return null;case`script`:return s=a.async,a=a.src,typeof a==`string`&&s&&typeof s!=`function`&&typeof s!=`symbol`?(s=mr(a),a=Li(f).hoistableScripts,c=a.get(s),c||(c={type:`script`,instance:null,count:0,state:null},a.set(s,c)),c):{type:`void`,instance:null,count:0,state:null};default:throw Error(r(444,e))}}function yr(e){return`href="`+on(e)+`"`}function Ia(e){return`link[rel="stylesheet"][`+e+`]`}function E0(e){return m({},e,{"data-precedence":e.precedence,precedence:null})}function W1(e,s,a,c){e.querySelector(`link[rel="preload"][as="style"][`+s+`]`)?c.loading=1:(s=e.createElement(`link`),c.preload=s,s.addEventListener(`load`,function(){return c.loading|=1}),s.addEventListener(`error`,function(){return c.loading|=2}),xe(s,`link`,a),de(s),e.head.appendChild(s))}function mr(e){return`[src="`+on(e)+`"]`}function Ha(e){return`script[async]`+e}function C0(e,s,a){if(s.count++,s.instance===null)switch(s.type){case`style`:var c=e.querySelector(`style[data-href~="`+on(a.href)+`"]`);if(c)return s.instance=c,de(c),c;var f=m({},a,{"data-href":a.href,"data-precedence":a.precedence,href:null,precedence:null});return c=(e.ownerDocument||e).createElement(`style`),de(c),xe(c,`style`,f),No(c,a.precedence,e),s.instance=c;case`stylesheet`:f=yr(a.href);var h=e.querySelector(Ia(f));if(h)return s.state.loading|=4,s.instance=h,de(h),h;c=E0(a),(f=yn.get(f))&&gh(c,f),h=(e.ownerDocument||e).createElement(`link`),de(h);var S=h;return S._p=new Promise(function(C,x){S.onload=C,S.onerror=x}),xe(h,`link`,c),s.state.loading|=4,No(h,a.precedence,e),s.instance=h;case`script`:return h=mr(a.src),(f=e.querySelector(Ha(h)))?(s.instance=f,de(f),f):(c=a,(f=yn.get(h))&&(c=m({},a),yh(c,f)),e=e.ownerDocument||e,f=e.createElement(`script`),de(f),xe(f,`link`,c),e.head.appendChild(f),s.instance=f);case`void`:return null;default:throw Error(r(443,s.type))}else s.type===`stylesheet`&&(s.state.loading&4)===0&&(c=s.instance,s.state.loading|=4,No(c,a.precedence,e));return s.instance}function No(e,s,a){for(var c=a.querySelectorAll(`link[rel="stylesheet"][data-precedence],style[data-precedence]`),f=c.length?c[c.length-1]:null,h=f,S=0;S title`):null)}function P1(e,s,a){if(a===1||s.itemProp!=null)return!1;switch(e){case`meta`:case`title`:return!0;case`style`:if(typeof s.precedence!=`string`||typeof s.href!=`string`||s.href===``)break;return!0;case`link`:if(typeof s.rel!=`string`||typeof s.href!=`string`||s.href===``||s.onLoad||s.onError)break;switch(s.rel){case`stylesheet`:return e=s.disabled,typeof s.precedence==`string`&&e==null;default:return!0}case`script`:if(s.async&&typeof s.async!=`function`&&typeof s.async!=`symbol`&&!s.onLoad&&!s.onError&&s.src&&typeof s.src==`string`)return!0}return!1}function T0(e){return!(e.type===`stylesheet`&&(e.state.loading&3)===0)}function tC(e,s,a,c){if(a.type===`stylesheet`&&(typeof c.media!=`string`||matchMedia(c.media).matches!==!1)&&(a.state.loading&4)===0){if(a.instance===null){var f=yr(c.href),h=s.querySelector(Ia(f));if(h){s=h._p,s!==null&&typeof s==`object`&&typeof s.then==`function`&&(e.count++,e=Bo.bind(e),s.then(e,e)),a.state.loading|=4,a.instance=h,de(h);return}h=s.ownerDocument||s,c=E0(c),(f=yn.get(f))&&gh(c,f),h=h.createElement(`link`),de(h);var S=h;S._p=new Promise(function(C,x){S.onload=C,S.onerror=x}),xe(h,`link`,c),a.instance=h}e.stylesheets===null&&(e.stylesheets=new Map),e.stylesheets.set(a,s),(s=a.state.preload)&&(a.state.loading&3)===0&&(e.count++,a=Bo.bind(e),s.addEventListener(`load`,a),s.addEventListener(`error`,a))}}var mh=0;function eC(e,s){return e.stylesheets&&e.count===0&&Io(e,e.stylesheets),0mh?50:800)+s);return e.unsuspend=a,function(){e.unsuspend=null,clearTimeout(c),clearTimeout(f)}}:null}function Bo(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Io(this,this.stylesheets);else if(this.unsuspend){var e=this.unsuspend;this.unsuspend=null,e()}}}var Lo=null;function Io(e,s){e.stylesheets=null,e.unsuspend!==null&&(e.count++,Lo=new Map,s.forEach(nC,e),Lo=null,Bo.call(e))}function nC(e,s){if(!(s.state.loading&4)){var a=Lo.get(e);if(a)var c=a.get(null);else{a=new Map,Lo.set(e,a);for(var f=e.querySelectorAll(`link[data-precedence],style[data-precedence]`),h=0;h`u`||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!=`function`))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(t){console.error(t)}}return n(),_h.exports=vC(),_h.exports}var wC=bC(),J=Jd();const EC={BASE_URL:`./`,DEV:!1,MODE:`production`,PROD:!0,SSR:!1,VITE_DS_TOKEN:`eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzZXJ2aWNlX2lkIjoic3ZjLWlycmVsZXZhbnQtYWFyZHdvbGYtb3B0dDA3c2lpdyIsImlhdCI6MTc3NDk3NjY0NH0.F67aNfIfZTYJHWg1hI8aFjlXlWqRRv1R9XdnRpRPCLg`,VITE_DS_URL:`https://api.electric-sql.cloud/v1/stream/svc-irrelevant-aardwolf-optt07siiw`,VITE_YJS_TOKEN:`eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzZXJ2aWNlX2lkIjoic3ZjLXlqcy1kZWFmLXRvdWNhbi1vNnZzbjA4ZTV0IiwiaWF0IjoxNzc0OTc2NjU4fQ.hP1i-w7N4NIYQUXGSMJDh8kL6JJaTTmh84Ha2e7qVbk`,VITE_YJS_URL:`https://api.electric-sql.cloud/v1/yjs/svc-yjs-deaf-toucan-o6vsn08e5t`},Uv=J.createContext(null);function Zd(){const n=J.useContext(Uv);if(!n)throw new Error(`useServerEndpoint must be used within ServerEndpointProvider`);return n}function Fo(n){const t=EC[n];if(!t)throw new Error(`Missing environment variable: ${n}`);return t}function CC({children:n}){const t=Fo(`VITE_YJS_URL`),i=Fo(`VITE_DS_URL`),r=J.useMemo(()=>({Authorization:`Bearer ${Fo(`VITE_YJS_TOKEN`)}`}),[]),l=J.useMemo(()=>({Authorization:`Bearer ${Fo(`VITE_DS_TOKEN`)}`}),[]),o=J.useMemo(()=>({yjsEndpoint:t,dsEndpoint:i,yjsHeaders:r,dsHeaders:l}),[t,i,r,l]);return F.jsx(Uv.Provider,{value:o,children:n})}const xC=`__includes_scalar__`;class _i{}class jr extends _i{constructor(t,i){super(),this.collection=t,this.alias=i,this.type=`collectionRef`}}class Sn extends _i{constructor(t,i){super(),this.query=t,this.alias=i,this.type=`queryRef`}}class Oe extends _i{constructor(t){super(),this.path=t,this.type=`ref`}}class Ue extends _i{constructor(t){super(),this.value=t,this.type=`val`}}class Ve extends _i{constructor(t,i){super(),this.name=t,this.args=i,this.type=`func`}}class zv extends _i{constructor(t,i){super(),this.name=t,this.args=i,this.type=`agg`}}class Ti extends _i{constructor(t,i,r,l,o,u,d=`collection`,p){super(),this.query=t,this.correlationField=i,this.childCorrelationField=r,this.fieldName=l,this.parentFilters=o,this.parentProjection=u,this.materialization=d,this.scalarField=p,this.type=`includesSubquery`}}function Br(n){return n instanceof zv||n instanceof Ve||n instanceof Oe||n instanceof Ue||n instanceof Ti}function Wd(n){return typeof n==`object`&&`expression`in n?n.expression:n}function J0(n){return typeof n==`object`&&`expression`in n?n.expression:n}function Z0(n){return typeof n==`object`&&`expression`in n&&n.residual===!0}function _C(n){return{expression:n,residual:!0}}function TC(n,t){if(n.from.alias===t)return n.from;for(const i of n.join||[])if(i.from.alias===t)return i.from}function ol(n,t,i){if(t.path.length!==0){if(t.path.length===1){const r=t.path[0];if(n.select){const l=n.select[r];if(l&&l.type===`ref`)return ol(n,l,i)}return{collection:i,path:[r]}}if(t.path.length>1){const[r,...l]=t.path,o=TC(n,r);return o?o.type===`queryRef`?ol(o.query,new Oe(l),i):{collection:o.collection,path:l}:void 0}}}class wn extends Error{constructor(t){super(t),this.name=`TanStackDBError`}}class W0 extends wn{constructor(t,i,r){const l=`${t===`insert`?`Insert`:`Update`} validation failed: ${i.map(o=>` +- ${o.message} - path: ${o.path}`).join(``)}`;super(r||l),this.name=`SchemaValidationError`,this.type=t,this.issues=i}}class Ai extends wn{constructor(t){super(t),this.name=`CollectionConfigurationError`}}class AC extends Ai{constructor(){super(`Collection requires a config`)}}class OC extends Ai{constructor(){super(`Collection requires a sync config`)}}class RC extends Ai{constructor(){super(`Schema must implement the standard-schema interface`)}}class P0 extends Ai{constructor(){super(`Schema validation must be synchronous`)}}class Cl extends wn{constructor(t){super(t),this.name=`CollectionStateError`}}class DC extends Cl{constructor(t,i){super(`Cannot perform ${t} on collection "${i}" - collection is in error state. Try calling cleanup() and restarting the collection.`)}}class MC extends Cl{constructor(t,i,r){super(`Invalid collection status transition from "${t}" to "${i}" for collection "${r}"`)}}class kC extends Cl{constructor(){super(`Collection is in error state`)}}class UC extends Cl{constructor(){super(`Active subscribers count is negative - this should never happen`)}}class $n extends wn{constructor(t){super(t),this.name=`CollectionOperationError`}}class zC extends $n{constructor(t){super(`An object was created without a defined key: ${JSON.stringify(t)}`)}}class NC extends $n{constructor(t,i){const r=t===null?`null`:typeof t;super(`getKey returned an invalid key type. Expected string or number, but got ${r}: ${JSON.stringify(t)}. Item: ${JSON.stringify(i)}`)}}class jC extends $n{constructor(t){super(`Cannot insert document with ID "${t}" because it already exists in the collection`)}}class BC extends $n{constructor(t,i,r){const l=`Cannot insert document with key "${t}" from sync because it already exists in the collection "${i}"`;r?.hasCustomGetKey&&r.hasDistinct?super(`${l}. This collection uses a custom getKey with .distinct(). The .distinct() operator deduplicates by the ENTIRE selected object (standard SQL behavior), but your custom getKey extracts only a subset of fields. This causes multiple distinct rows (with different values in non-key fields) to receive the same key. To fix this, either: (1) ensure your SELECT only includes fields that uniquely identify each row, (2) use .groupBy() with min()/max() aggregates to select one value per group, or (3) remove the custom getKey to use the default key behavior.`):r?.hasCustomGetKey&&r.hasJoins?super(`${l}. This collection uses a custom getKey with joined queries. Joined queries can produce multiple rows with the same key when relationships are not 1:1. Consider: (1) using a composite key in your getKey function (e.g., \`\${item.key1}-\${item.key2}\`), (2) ensuring your join produces unique rows per key, or (3) removing the custom getKey to use the default composite key behavior.`):super(l)}}class LC extends $n{constructor(){super(`The first argument to update is missing`)}}class IC extends $n{constructor(){super(`No keys were passed to update`)}}class HC extends $n{constructor(t){super(`The key "${t}" was passed to update but an object for this key was not found in the collection`)}}class qC extends $n{constructor(t,i){super(`Updating the key of an item is not allowed. Original key: "${t}", Attempted new key: "${i}". Please delete the old item and create a new one if a key change is necessary.`)}}class KC extends $n{constructor(){super(`No keys were passed to delete`)}}class VC extends $n{constructor(t){super(`Collection.delete was called with key '${t}' but there is no item in the collection with this key`)}}class Pd extends wn{constructor(t){super(t),this.name=`MissingHandlerError`}}class $C extends Pd{constructor(){super(`Collection.insert called directly (not within an explicit transaction) but no 'onInsert' handler is configured.`)}}class GC extends Pd{constructor(){super(`Collection.update called directly (not within an explicit transaction) but no 'onUpdate' handler is configured.`)}}class YC extends Pd{constructor(){super(`Collection.delete called directly (not within an explicit transaction) but no 'onDelete' handler is configured.`)}}class ys extends wn{constructor(t){super(t),this.name=`TransactionError`}}class FC extends ys{constructor(){super(`mutationFn is required when creating a transaction`)}}class QC extends ys{constructor(){super(`onMutate must be synchronous and cannot return a promise. Remove async/await or returned promises from onMutate.`),this.name=`OnMutateMustBeSynchronousError`}}class XC extends ys{constructor(){super(`You can no longer call .mutate() as the transaction is no longer pending`)}}class JC extends ys{constructor(){super(`You can no longer call .rollback() as the transaction is already completed`)}}class ZC extends ys{constructor(){super(`You can no longer call .commit() as the transaction is no longer pending`)}}class Dh extends ys{constructor(){super(`No pending sync transaction to write to`)}}class Mh extends ys{constructor(){super(`The pending sync transaction is already committed, you can't still write to it.`)}}class WC extends ys{constructor(){super(`No pending sync transaction to commit`)}}class PC extends ys{constructor(){super(`The pending sync transaction is already committed, you can't commit it again.`)}}class Oi extends wn{constructor(t){super(t),this.name=`QueryBuilderError`}}class tx extends Oi{constructor(t){super(`Only one source is allowed in the ${t}`)}}class ex extends Oi{constructor(t){super(`A sub query passed to a ${t} must have a from clause itself`)}}class nx extends Oi{constructor(t){super(`Invalid source for live query: The value provided for alias "${t}" is not a Collection or subquery. Live queries only accept Collection instances or subqueries. Please ensure you're passing a valid Collection or QueryBuilder, not a plain array or other data type.`)}}class Qo extends Oi{constructor(t,i){super(`Invalid source for ${t}: Expected an object with a single key-value pair like { alias: collection }. For example: .from({ todos: todosCollection }). Got: ${i}`)}}class sx extends Oi{constructor(){super(`Join condition must be an equality expression`)}}class ix extends Oi{constructor(){super(`Query must have a from clause`)}}class tS extends Oi{constructor(t){super(`Invalid where() expression: Expected a query expression, but received a ${t}. This usually happens when using JavaScript's comparison operators (===, !==, <, >, etc.) directly. Instead, use the query builder functions: + + ❌ .where(({ user }) => user.id === 'abc') + ✅ .where(({ user }) => eq(user.id, 'abc')) + +Available comparison functions: eq, gt, gte, lt, lte, and, or, not, like, ilike, isNull, isUndefined`)}}class ze extends wn{constructor(t){super(t),this.name=`QueryCompilationError`}}class rx extends ze{constructor(){super(`DISTINCT requires a SELECT clause.`)}}class ax extends ze{constructor(){super(`fn.select() cannot be used with groupBy(). groupBy requires the compiler to statically analyze aggregate functions (count, sum, max, etc.) in the SELECT clause, which is not possible with fn.select() since it is an opaque function. Use .select() instead of .fn.select() when combining with groupBy().`)}}class lx extends ze{constructor(){super(`Top-level scalar select() is not supported by createLiveQueryCollection() or queryOnce(). Return an object from .select(), or use the scalar query inside toArray(...) or concat(toArray(...)).`)}}class ox extends ze{constructor(){super(`HAVING clause requires GROUP BY clause`)}}class cx extends ze{constructor(){super(`LIMIT and OFFSET require an ORDER BY clause to ensure deterministic results`)}}class Nv extends ze{constructor(t,i,r){const l=i?`alias "${t}" (collection "${i}")`:`collection "${t}"`,o=r?.length?`. Available keys: ${r.join(`, `)}`:``;super(`Input for ${l} not found in inputs map${o}`)}}class ux extends ze{constructor(t,i){super(`Subquery uses alias "${t}" which is already used in the parent query. Each alias must be unique across parent and subquery contexts. Parent query aliases: ${i.join(`, `)}. Please rename "${t}" in either the parent query or subquery to avoid conflicts.`)}}class fx extends ze{constructor(t){super(`Unsupported FROM type: ${t}`)}}class hx extends ze{constructor(t){super(`Unknown expression type: ${t}`)}}class dx extends ze{constructor(){super(`Reference path cannot be empty`)}}class px extends ze{constructor(t){super(`Unknown function: ${t}`)}}class eS extends ze{constructor(t){super(`Collection "${t}" not found during compilation of join`)}}class Ri extends wn{constructor(t){super(t),this.name=`JoinError`}}class gx extends Ri{constructor(t){super(`Unsupported join type: ${t}`)}}class yx extends Ri{constructor(t){super(`Invalid join condition: both expressions refer to the same source "${t}"`)}}class mx extends Ri{constructor(){super(`Invalid join condition: expressions must reference source aliases`)}}class Sx extends Ri{constructor(t){super(`Invalid join condition: left expression refers to an unavailable source "${t}"`)}}class vx extends Ri{constructor(t){super(`Invalid join condition: right expression does not refer to the joined source "${t}"`)}}class bx extends Ri{constructor(){super(`Invalid join condition`)}}class wx extends Ri{constructor(t){super(`Unsupported join source type: ${t}`)}}class Vc extends wn{constructor(t){super(t),this.name=`GroupByError`}}class Ex extends Vc{constructor(t){super(`Non-aggregate expression '${t}' in SELECT must also appear in GROUP BY clause`)}}class Cx extends Vc{constructor(t){super(`Unsupported aggregate function: ${t}`)}}class xx extends Vc{constructor(t){super(`Aggregate function in HAVING clause must also be in SELECT clause: ${t}`)}}class _x extends Vc{constructor(t){super(`Unknown expression type in HAVING clause: ${t}`)}}class nS extends wn{constructor(t,i){const r=i instanceof Error?i.message:String(i);super(`Collection "${t}" sync cleanup function threw an error: ${r}`),this.name=`SyncCleanupError`}}class Tx extends wn{constructor(t){super(t),this.name=`QueryOptimizerError`}}class Ax extends Tx{constructor(){super(`Cannot combine empty expression list`)}}class Ox extends ze{constructor(t,i,r,l){super(`Internal error: subscription for alias '${t}' (remapped from '${i}', collection '${r}') is missing in join pipeline. Available aliases: ${l.join(`, `)}. This indicates a bug in alias tracking.`)}}class Rx extends ze{constructor(t){super(`Internal error: compiler returned aliases without inputs: ${t.join(`, `)}. This indicates a bug in query compilation. Please report this issue.`)}}class Dx extends ze{constructor(){super(`setWindow() can only be called on collections with an ORDER BY clause. Add .orderBy() to your query to enable window movement.`)}}function Bn(n,t){return rc(n,t,new Map)}function rc(n,t,i){if(n===t)return!0;if(n==null||t==null||typeof n!=typeof t)return!1;if(n instanceof Date)return t instanceof Date?n.getTime()===t.getTime():!1;if(t instanceof Date)return!1;if(n instanceof RegExp)return t instanceof RegExp?n.source===t.source&&n.flags===t.flags:!1;if(t instanceof RegExp)return!1;if(n instanceof Map){if(!(t instanceof Map)||n.size!==t.size)return!1;if(i.has(n))return i.get(n)===t;i.set(n,t);const l=Array.from(n.entries()).every(([o,u])=>t.has(o)&&rc(u,t.get(o),i));return i.delete(n),l}if(t instanceof Map)return!1;if(n instanceof Set){if(!(t instanceof Set)||n.size!==t.size)return!1;if(i.has(n))return i.get(n)===t;i.set(n,t);const r=Array.from(n),l=Array.from(t);if(r.every(u=>typeof u!=`object`))return i.delete(n),r.every(u=>t.has(u));const o=r.length===l.length;return i.delete(n),o}if(t instanceof Set)return!1;if(ArrayBuffer.isView(n)&&ArrayBuffer.isView(t)&&!(n instanceof DataView)&&!(t instanceof DataView)){const r=n,l=t;if(r.length!==l.length)return!1;for(let o=0;orc(l,t[o],i));return i.delete(n),r}if(Array.isArray(t))return!1;if(typeof n==`object`){if(i.has(n))return i.get(n)===t;i.set(n,t);const r=Object.keys(n),l=Object.keys(t);if(r.length!==l.length)return i.delete(n),!1;const o=r.every(u=>u in t&&rc(n[u],t[u],i));return i.delete(n),o}return!1}const Mx=new Set([`Temporal.Duration`,`Temporal.Instant`,`Temporal.PlainDate`,`Temporal.PlainDateTime`,`Temporal.PlainMonthDay`,`Temporal.PlainTime`,`Temporal.PlainYearMonth`,`Temporal.ZonedDateTime`]);function Xs(n){if(n==null||typeof n!=`object`)return!1;const t=n[Symbol.toStringTag];return typeof t==`string`&&Mx.has(t)}const jv={direction:`asc`,nulls:`first`,stringSort:`locale`},kh=new WeakMap;let kx=1;function sS(n){if(kh.has(n))return kh.get(n);const t=kx++;return kh.set(n,t),t}const tp=(n,t,i)=>{const{nulls:r}=i;if(n==null&&t==null)return 0;if(n==null)return r===`first`?-1:1;if(t==null)return r===`first`?1:-1;if(typeof n==`string`&&typeof t==`string`&&i.stringSort===`locale`)return n.localeCompare(t,i.locale,i.localeOptions);if(Array.isArray(n)&&Array.isArray(t)){for(let u=0;ud?1:0}const l=typeof n==`object`,o=typeof t==`object`;if(l||o){if(l&&o){const u=sS(n),d=sS(t);return u-d}if(l)return 1;if(o)return-1}return nt?1:0},Ux=(n,t,i)=>tp(t,n,{...i,nulls:i.nulls===`first`?`last`:`first`});function Pa(n){return(t,i)=>n.direction===`asc`?tp(t,i,n):Ux(t,i,n)}const zx=Pa({direction:`asc`,nulls:`first`,stringSort:`locale`});function Nx(n,t){if(n.byteLength!==t.byteLength)return!1;for(let i=0;ii}case`ref`:return t?Hx(n):Ix(n);case`func`:return qx(n,t);default:throw new hx(n.type)}}function Ix(n){const[t,...i]=n.path;if(!t)throw new dx;if(t===`$selected`){if(i.length===0)return l=>l.$selected;if(i.length===1){const l=i[0];return o=>o.$selected?.[l]}else return l=>{const o=l.$selected;if(o===void 0)return;let u=o;for(const d of i){if(u==null)return u;u=u[d]}return u}}const r=t;if(i.length===0)return l=>l[r];if(i.length===1){const l=i[0];return o=>o[r]?.[l]}else return l=>{const o=l[r];if(o===void 0)return;let u=o;for(const d of i){if(u==null)return u;u=u[d]}return u}}function Hx(n){const t=n.path;return i=>{let r=i;for(const l of t){if(r==null)return r;r=r[l]}return r}}function qx(n,t){const i=n.args.map(r=>ep(r,t));switch(n.name){case`eq`:{const r=i[0],l=i[1];return o=>{const u=xr(r(o)),d=xr(l(o));return ge(u)||ge(d)?null:Bx(u,d)}}case`gt`:{const r=i[0],l=i[1];return o=>{const u=r(o),d=l(o);return ge(u)||ge(d)?null:u>d}}case`gte`:{const r=i[0],l=i[1];return o=>{const u=r(o),d=l(o);return ge(u)||ge(d)?null:u>=d}}case`lt`:{const r=i[0],l=i[1];return o=>{const u=r(o),d=l(o);return ge(u)||ge(d)?null:u{const u=r(o),d=l(o);return ge(u)||ge(d)?null:u<=d}}case`and`:return r=>{let l=!1;for(const o of i){const u=o(r);if(u===!1)return!1;ge(u)&&(l=!0)}return l?null:!0};case`or`:return r=>{let l=!1;for(const o of i){const u=o(r);if(u===!0)return!0;ge(u)&&(l=!0)}return l?null:!1};case`not`:{const r=i[0];return l=>{const o=r(l);return ge(o)?null:!o}}case`in`:{const r=i[0],l=i[1];return o=>{const u=xr(r(o)),d=l(o);return ge(u)?null:Array.isArray(d)?d.some(p=>xr(p)===u):!1}}case`like`:{const r=i[0],l=i[1];return o=>{const u=r(o),d=l(o);return ge(u)||ge(d)?null:iS(u,d,!1)}}case`ilike`:{const r=i[0],l=i[1];return o=>{const u=r(o),d=l(o);return ge(u)||ge(d)?null:iS(u,d,!0)}}case`upper`:{const r=i[0];return l=>{const o=r(l);return typeof o==`string`?o.toUpperCase():o}}case`lower`:{const r=i[0];return l=>{const o=r(l);return typeof o==`string`?o.toLowerCase():o}}case`length`:{const r=i[0];return l=>{const o=r(l);return typeof o==`string`||Array.isArray(o)?o.length:0}}case`concat`:return r=>i.map(l=>{const o=l(r);try{return String(o??``)}catch{try{return JSON.stringify(o)||``}catch{return`[object]`}}}).join(``);case`coalesce`:return r=>{for(const l of i){const o=l(r);if(o!=null)return o}return null};case`add`:{const r=i[0],l=i[1];return o=>{const u=r(o),d=l(o);return(u??0)+(d??0)}}case`subtract`:{const r=i[0],l=i[1];return o=>{const u=r(o),d=l(o);return(u??0)-(d??0)}}case`multiply`:{const r=i[0],l=i[1];return o=>{const u=r(o),d=l(o);return(u??0)*(d??0)}}case`divide`:{const r=i[0],l=i[1];return o=>{const u=r(o),p=l(o)??0;return p!==0?(u??0)/p:null}}case`date`:{const r=i[0];return l=>{const o=r(l),u=Uh(o);return u?u.toISOString().slice(0,10):null}}case`datetime`:{const r=i[0];return l=>{const o=r(l),u=Uh(o);return u?u.toISOString():null}}case`strftime`:{const r=i[0],l=i[1];return o=>{const u=r(o);if(typeof u!=`string`)return null;const d=l(o),p=Uh(d);return p?Lx(u,p):null}}case`isUndefined`:{const r=i[0];return l=>r(l)===void 0}case`isNull`:{const r=i[0];return l=>r(l)===null}default:throw new px(n.name)}}function iS(n,t,i){if(typeof n!=`string`||typeof t!=`string`)return!1;const r=i?n.toLowerCase():n;let o=(i?t.toLowerCase():t).replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);return o=o.replace(/%/g,`.*`),o=o.replace(/_/g,`.`),new RegExp(`^${o}$`,`s`).test(r)}class Kx{constructor(t){this.originalIndex=t}lookup(t,i){const r=t===`gt`?`lt`:t===`gte`?`lte`:t===`lt`?`gt`:t===`lte`?`gte`:t;return this.originalIndex.lookup(r,i)}rangeQuery(t={}){return this.originalIndex.rangeQueryReversed(t)}rangeQueryReversed(t={}){return this.originalIndex.rangeQuery(t)}take(t,i,r){return this.originalIndex.takeReversed(t,i,r)}takeFromStart(t,i){return this.originalIndex.takeReversedFromEnd(t,i)}takeReversed(t,i,r){return this.originalIndex.take(t,i,r)}takeReversedFromEnd(t,i){return this.originalIndex.takeFromStart(t,i)}get orderedEntriesArray(){return this.originalIndex.orderedEntriesArrayReversed}get orderedEntriesArrayReversed(){return this.originalIndex.orderedEntriesArray}supports(t){return this.originalIndex.supports(t)}matchesField(t){return this.originalIndex.matchesField(t)}matchesCompareOptions(t){return this.originalIndex.matchesCompareOptions(t)}matchesDirection(t){return this.originalIndex.matchesDirection(t)}getStats(){return this.originalIndex.getStats()}add(t,i){this.originalIndex.add(t,i)}remove(t,i){this.originalIndex.remove(t,i)}update(t,i,r){this.originalIndex.update(t,i,r)}build(t){this.originalIndex.build(t)}clear(){this.originalIndex.clear()}get keyCount(){return this.originalIndex.keyCount}equalityLookup(t){return this.originalIndex.equalityLookup(t)}inArrayLookup(t){return this.originalIndex.inArrayLookup(t)}get indexedKeysSet(){return this.originalIndex.indexedKeysSet}get valueMapData(){return this.originalIndex.valueMapData}}function rS(n,t,i,r,l){const o=n;return{...n,$synced:o.$synced??r(),$origin:o.$origin??l(),$key:o.$key??t,$collectionId:o.$collectionId??i}}const pd=[`$synced`,`$origin`,`$key`,`$collectionId`];function Vx(n){return pd.includes(n)}function Lv(n){return n.some(t=>Vx(t))}function xl(n,t,i){if(Lv(t))return;const r=i??{...jv,...n.compareOptions};for(const l of n.indexes.values())if(l.matchesField(t)&&l.matchesCompareOptions(r))return l.matchesDirection(r.direction)?l:new Kx(l)}function $x(n){if(n.length===0)return new Set;if(n.length===1)return new Set(n[0]);let t=new Set(n[0]);for(let i=1;i=2){const o=r.split(`.`),u=xl(t,o);if(u&&u.supports(`gt`)&&u.supports(`lt`)){let d,p,g=!0,y=!0;for(const{operation:v,value:w}of l)switch(v){case`gt`:(d===void 0||w>d)&&(d=w,g=!1);break;case`gte`:(d===void 0||w>d)&&(d=w,g=!0);break;case`lt`:(p===void 0||w0){const l=r.map(u=>u.matchingKeys);return{canOptimize:!0,matchingKeys:$x(l)}}return{canOptimize:!1,matchingKeys:new Set}}function Jx(n,t){if(n.type!==`func`||n.args.length<2)return{canOptimize:!1,matchingKeys:new Set};const i=[];for(const r of n.args){const l=np(r,t);l.canOptimize&&i.push(l)}if(i.length>0){const r=i.map(o=>o.matchingKeys);return{canOptimize:!0,matchingKeys:Gx(r)}}return{canOptimize:!1,matchingKeys:new Set}}function Zx(n,t){if(n.type!==`func`||n.args.length!==2)return{canOptimize:!1,matchingKeys:new Set};const i=n.args[0],r=n.args[1];if(i.type===`ref`&&r.type===`val`&&Array.isArray(r.value)){const l=i.path,o=r.value,u=xl(t,l);if(u){if(u.supports(`in`))return{canOptimize:!0,matchingKeys:u.lookup(`in`,o)};if(u.supports(`eq`)){const d=new Set;for(const p of o){const g=u.lookup(`eq`,p);for(const y of g)d.add(y)}return{canOptimize:!0,matchingKeys:d}}}}return{canOptimize:!1,matchingKeys:new Set}}function Iv(n){return n.config.autoIndex===`eager`}function $c(n,t,i,r,l){if(Lv(t)||!Iv(i))return;const o=r??{...jv,...i.compareOptions};if(!Array.from(i.indexes.values()).find(d=>d.matchesField(t)&&d.matchesCompareOptions(o)))try{i.createIndex(d=>{let p=d;for(const g of t)p=p[g];return p},{name:`auto:${t.join(`.`)}`,options:l?{compareFn:l,compareOptions:o}:{}})}catch(d){console.warn(`${i.id?`[${i.id}] `:``}Failed to create auto-index for field path "${t.join(`.`)}":`,d)}}function Wx(n,t){if(!Iv(t))return;const i=Px(n);for(const{fieldName:r,fieldPath:l}of i)$c(r,l,t)}function Px(n){const t=[];function i(r){if(r.type!==`func`)return;const l=r;if(l.name===`and`){for(const g of l.args)i(g);return}if(![`eq`,`gt`,`gte`,`lt`,`lte`,`in`].includes(l.name)||l.args.length<1||l.args[0].type!==`ref`)return;const d=l.args[0].path;if(d.length===0)return;const p=d.join(`_`);t.push({fieldName:p,fieldPath:d})}return i(n),t}class t_ extends Map{constructor(t,i){super(i),this.defaultValue=t}get(t){return this.has(t)?super.get(t):this.defaultValue()}update(t,i){const r=this.get(t),l=i(r);return this.set(t,l),l}}const zh=3e4;function Nh(n,t){if(t.length<=zh)n.push(...t);else for(let i=0;i0)l=o;else return o}return r}class n_{constructor(){this.objectIds=new WeakMap,this.nextId=0}getId(t){if(typeof t!=`object`||t===null){const i=String(t);let r=0;for(let l=0;lt?1:0:typeof n==`string`?-1:1}function cl(n){return JSON.stringify(n,(t,i)=>typeof i==`bigint`?i.toString():i instanceof Date?i.toISOString():i)}const i_=Se(),r_=Se(),a_=Se(),l_=Se(),o_=Se();function Se(){return Math.random()*(2**31-1)>>>0}const Hv=new ArrayBuffer(8),c_=new DataView(Hv),$s=new Uint8Array(Hv);class _l{constructor(){this.hash=i_,this.length=0,this.carry=0,this.carryBytes=0}_mix(t){t=Math.imul(t,3432918353),t=t<<15|t>>>17,t=Math.imul(t,461845907),this.hash^=t,this.hash=this.hash<<13|this.hash>>>19,this.hash=Math.imul(this.hash,5)+3864292196}writeByte(t){this.carry|=(t&255)<<8*this.carryBytes,this.carryBytes++,this.length++,this.carryBytes===4&&(this._mix(this.carry>>>0),this.carry=0,this.carryBytes=0)}update(t){switch(typeof t){case`symbol`:{this.update(o_);const i=t.description;if(!i)return;for(let r=0;r>>8&255)}return}case`string`:this.update(r_);for(let i=0;i>>8&255)}return;case`number`:c_.setFloat64(0,t,!0),this.writeByte($s[0]),this.writeByte($s[1]),this.writeByte($s[2]),this.writeByte($s[3]),this.writeByte($s[4]),this.writeByte($s[5]),this.writeByte($s[6]),this.writeByte($s[7]);return;case`bigint`:{let i=t;for(i<0n?(i=-i,this.update(l_)):this.update(a_);i>0n;)this.writeByte(Number(i&0xffn)),i>>=8n;t===0n&&this.writeByte(0);return}default:throw new TypeError(`Unsupported input type: ${typeof t}`)}}digest(){if(this.carryBytes>0){let t=this.carry>>>0;t=Math.imul(t,3432918353),t=t<<15|t>>>17,t=Math.imul(t,461845907),this.hash^=t}return this.hash^=this.length,this.hash^=this.hash>>>16,this.hash=Math.imul(this.hash,2246822507),this.hash^=this.hash>>>13,this.hash=Math.imul(this.hash,3266489909),this.hash^=this.hash>>>16,this.hash>>>0}}const u_=Se(),f_=Se(),h_=Se(),d_=Se(),p_=Se(),g_=Se(),y_=Se(),m_=Se(),S_=Se(),v_=Se(),b_=Se(),w_=Se(),E_=Se(),C_=new Set([`Temporal.Duration`,`Temporal.Instant`,`Temporal.PlainDate`,`Temporal.PlainDateTime`,`Temporal.PlainMonthDay`,`Temporal.PlainTime`,`Temporal.PlainYearMonth`,`Temporal.ZonedDateTime`]);function x_(n){const t=n[Symbol.toStringTag];return typeof t==`string`&&C_.has(t)}const __=128,ul=new WeakMap;function ke(n){const t=new _l;return qv(t,n),t.digest()}function T_(n){const t=ul.get(n);if(t!==void 0)return t;let i;if(n instanceof Date)i=A_(n);else if(typeof Buffer<`u`&&n instanceof Buffer||n instanceof Uint8Array)if(n.byteLength<=__)i=O_(n);else return yd(n);else{if(n instanceof File)return yd(n);if(x_(n))i=R_(n);else{let r=n,l=m_;n instanceof Array&&(l=S_),n instanceof Map&&(l=v_,r=[...n.entries()]),n instanceof Set&&(l=b_,r=[...n.entries()]),i=D_(r,l)}}return ul.set(n,i),i}function A_(n){const t=new _l;return t.update(y_),t.update(n.getTime()),t.digest()}function O_(n){const t=new _l;t.update(w_),t.update(n.byteLength);for(let i=0;i[t(i),r]))}filter(t){return new ee(this.#t.filter(([i,r])=>t(i)))}negate(){return new ee(this.#t.map(([t,i])=>[t,-i]))}concat(t){const i=[];return Nh(i,this.#t),Nh(i,t.getInner()),new ee(i)}consolidate(){if(this.#t.length>0){const t=this.#t[0]?.[0];if(Array.isArray(t)&&t.length===2)return this.#e()}return this.#n()}#e(){const t=new Map,i=new Map,r=o=>{if(o.length!==2)throw new Error(`Expected tuple of length 2`);const[u,d]=o;return`${jh.getStringId(u)}|${jh.getStringId(d)}`};for(const[o,u]of this.#t){if(!Array.isArray(o)||o.length!==2)return this.#n();const[d,p]=o;if(typeof d!=`string`&&typeof d!=`number`)return this.#n();let g;Array.isArray(p)&&p.length===2?g=r(p):g=jh.getStringId(p);const y=d+`|`+g;t.set(y,(t.get(y)||0)+u),i.has(y)||i.set(y,o)}const l=[];for(const[o,u]of t)u!==0&&l.push([i.get(o),u]);return new ee(l)}#n(){const t=new t_(()=>0),i=new Map;let r=!1,l=!1,o=!1;for(const[p,g]of this.#t)if(typeof p==`string`)r=!0;else if(typeof p==`number`)l=!0;else{o=!0;break}const u=o||r&&l;for(const[p,g]of this.#t){const y=u?ke(p):p;u&&!i.has(y)&&i.set(y,p),t.update(y,m=>m+g)}const d=[];for(const[p,g]of t.entries())if(g!==0){const y=u?i.get(p):p;d.push([y,g])}return new ee(d)}extend(t){const i=t instanceof ee?t.getInner():t;Nh(this.#t,i)}add(t,i){i!==0&&this.#t.push([t,i])}getInner(){return this.#t}}class U_{#t;constructor(t){this.#t=t}drain(){const t=[...this.#t].reverse();return this.#t.length=0,t}isEmpty(){return this.#t.length===0}}class Rn{#t=[];sendData(t){t instanceof ee||(t=new ee(t));for(const i of this.#t)i.unshift(t)}newReader(){const t=[];return this.#t.push(t),new U_(t)}}class Kv{constructor(t,i,r){this.id=t,this.inputs=i,this.output=r}hasPendingWork(){return this.inputs.some(t=>!t.isEmpty())}}class Di extends Kv{constructor(t,i,r){super(t,[i],r),this.id=t}inputMessages(){return this.inputs[0].drain()}}class z_ extends Kv{constructor(t,i,r,l){super(t,[i,r],l),this.id=t}inputAMessages(){return this.inputs[0].drain()}inputBMessages(){return this.inputs[1].drain()}}class sp extends Di{run(){for(const t of this.inputMessages())this.output.sendData(this.inner(t))}}class N_{#t=[];#e=0;#n=!1;constructor(){}#s(){if(this.#n)throw new Error(`Graph already finalized`)}getNextOperatorId(){return this.#s(),this.#e++}newInput(){this.#s();const t=new Rn;return new j_(this,t)}addOperator(t){this.#s(),this.#t.push(t)}finalize(){this.#s(),this.#n=!0}step(){if(!this.#n)throw new Error(`Graph not finalized`);for(const t of this.#t)t.run()}pendingWork(){return this.#t.some(t=>t.hasPendingWork())}run(){for(;this.pendingWork();)this.step()}}class Dn{#t;#e;constructor(t,i){this.#t=t,this.#e=i}connectReader(){return this.#e.newReader()}get writer(){return this.#e}get graph(){return this.#t}pipe(...t){return t.reduce((i,r)=>r(i),this)}}class j_ extends Dn{sendData(t){this.writer.sendData(t)}}class B_ extends Di{run(){const t=this.inputMessages();if(t.length===0)return;const i=new ee;for(const l of t)i.extend(l);const r=i.consolidate();r.getInner().length>0&&this.output.sendData(r)}}function Vv(){return n=>{const t=new Dn(n.graph,new Rn),i=new B_(n.graph.getNextOperatorId(),n.connectReader(),t.writer);return n.graph.addOperator(i),t}}const Qa=Symbol(`NO_PREFIX`);class lS extends Map{addValue(t,i){if(i===0)return this.size===0;const r=tl(t),l=this.get(r);if(ac(l)){const[o,u]=l;if(tl(o)!==r)throw new Error(`Mismatching prefixes, this should never happen`);if(o===t||ke(o)===ke(t)){const p=u+i;p===0?this.delete(r):this.set(r,[t,p])}else{const p=new Xa;p.set(ke(o),l),p.set(ke(t),[t,i]),this.set(r,p)}}else l===void 0?this.set(r,[t,i]):l.addValue(t,i)&&this.delete(r);return this.size===0}}class Xa extends Map{addValue(t,i){if(i===0)return this.size===0;const r=ke(t),l=this.get(r);if(l){const[,o]=l,u=o+i;u===0?this.delete(r):this.set(r,[t,u])}else this.set(r,[t,i]);return this.size===0}}class Fs{#t;#e=new Map;constructor(){this.#t=new Map}static fromMultiSets(t){const i=new Fs;for(const r of t)for(const[l,o]of r.getInner()){const[u,d]=l;i.addValue(u,[d,o])}return i}toString(t=!1){return`Index(${JSON.stringify([...this.entries()],void 0,t?2:void 0)})`}get size(){return this.#t.size}has(t){return this.#t.has(t)}hasPresence(t){return(this.#e.get(t)||0)!==0}getConsolidatedMultiplicity(t){return this.#e.get(t)||0}getPresenceKeys(){return this.#e.keys()}get(t){return[...this.getIterator(t)]}*getIterator(t){const i=this.#t.get(t);if(ac(i))yield i;else{if(i===void 0)return;if(i instanceof Xa)for(const r of i.values())yield r;else for(const r of i.values())if(ac(r))yield r;else for(const l of r.values())yield l}}*entries(){for(const t of this.#t.keys())for(const i of this.getIterator(t))yield[t,i]}*entriesIterators(){for(const t of this.#t.keys())yield[t,this.getIterator(t)]}addValue(t,i){const[r,l]=i;if(l===0)return;const o=(this.#e.get(t)||0)+l;o===0?this.#e.delete(t):this.#e.set(t,o);const u=this.#t.get(t);if(u===void 0){this.#t.set(t,i);return}if(ac(u)){this.#n(t,u,r,l);return}if(u instanceof Xa){const d=tl(r);if(d!==Qa){const p=new lS;p.set(Qa,u),p.set(d,i),this.#t.set(t,p)}else u.addValue(r,l)&&this.#t.delete(t)}else u.addValue(r,l)&&this.#t.delete(t)}#n(t,i,r,l){const[o,u]=i;if(o===r){const g=u+l;g===0?this.#t.delete(t):this.#t.set(t,[r,g]);return}const d=tl(r),p=tl(o);if(p===d&&(o===r||ke(o)===ke(r))){const g=u+l;g===0?this.#t.delete(t):this.#t.set(t,[r,g]);return}if(p===Qa&&d===Qa){const g=new Xa;g.set(ke(o),i),g.set(ke(r),[r,l]),this.#t.set(t,g)}else{const g=new lS;if(p===d){const y=new Xa;y.set(ke(o),i),y.set(ke(r),[r,l]),g.set(p,y)}else g.set(p,i),g.set(d,[r,l]);this.#t.set(t,g)}}append(t){for(const[i,r]of t.entries())this.addValue(i,r)}join(t){const i=[];if(this.size<=t.size)for(const[r,l]of this.entriesIterators()){if(!t.has(r))continue;const o=t.get(r);for(const[u,d]of l)for(const[p,g]of o)d!==0&&g!==0&&i.push([[r,[u,p]],d*g])}else for(const[r,l]of t.entriesIterators()){if(!this.has(r))continue;const o=this.get(r);for(const[u,d]of l)for(const[p,g]of o)g!==0&&d!==0&&i.push([[r,[p,u]],g*d])}return new ee(i)}}function tl(n){return Array.isArray(n)&&(typeof n[0]==`string`||typeof n[0]==`number`||typeof n[0]==`bigint`)?n[0]:Qa}function ac(n){return Array.isArray(n)}class L_ extends Di{#t=new Fs;#e=new Fs;#n;constructor(t,i,r,l){super(t,i,r),this.#n=l}run(){const t=new Set;for(const r of this.inputMessages())for(const[l,o]of r.getInner()){const[u,d]=l;this.#t.addValue(u,[d,o]),t.add(u)}const i=[];for(const r of t){const l=this.#t.get(r),o=this.#e.get(r),u=this.#n(l),d=new Map,p=new Map;for(const[g,y]of u){const m=d.get(g)??0;d.set(g,m+y)}for(const[g,y]of o){const m=p.get(g)??0;p.set(g,m+y)}for(const[g,y]of p)d.has(g)||(i.push([[r,g],-y]),this.#e.addValue(r,[g,-y]));for(const[g,y]of d)p.has(g)||y!==0&&(i.push([[r,g],y]),this.#e.addValue(r,[g,y]));for(const[g,y]of d){const m=p.get(g);if(m!==void 0){const v=y-m;v!==0&&(i.push([[r,g],v]),this.#e.addValue(r,[g,v]))}}}i.length>0&&this.output.sendData(new ee(i))}}function $v(n){return t=>{const i=new Dn(t.graph,new Rn),r=new L_(t.graph.getNextOperatorId(),t.connectReader(),i.writer,n);return t.graph.addOperator(r),i}}class I_ extends Di{#t;#e;constructor(t,i,r,l=o=>o){super(t,i,r),this.#t=l,this.#e=new Map}run(){const t=new Map;for(const r of this.inputMessages())for(const[l,o]of r.getInner()){const u=ke(this.#t(l)),p=(t.get(u)?.[0]??this.#e.get(u)??0)+o;t.set(u,[p,l])}const i=[];for(const[r,[l,o]]of t.entries()){const u=this.#e.get(r)??0;l===0?this.#e.delete(r):this.#e.set(r,l),u<=0&&l>0?i.push([[ke(this.#t(o)),o[1]],1]):u>0&&l<=0&&i.push([[ke(this.#t(o)),o[1]],-1])}i.length>0&&this.output.sendData(new ee(i))}}function H_(n=t=>t){return t=>{const i=new Dn(t.graph,new Rn),r=new I_(t.graph.getNextOperatorId(),t.connectReader(),i.writer,n);return t.graph.addOperator(r),i}}class q_ extends sp{#t;constructor(t,i,r,l){super(t,i,r),this.#t=l}inner(t){return t.filter(this.#t)}}function ps(n){return t=>{const i=new Dn(t.graph,new Rn),r=new q_(t.graph.getNextOperatorId(),t.connectReader(),i.writer,n);return t.graph.addOperator(r),i}}const K_=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`;function _r(n,t,i){const r=i[0];if(t!=null&&n>=t)throw new Error(n+` >= `+t);if(n.slice(-1)===r||t&&t.slice(-1)===r)throw new Error(`trailing zero`);if(t){let u=0;for(;(n[u]||r)===t[u];)u++;if(u>0)return t.slice(0,u)+_r(n.slice(u),t.slice(u),i)}const l=n?i.indexOf(n[0]):0,o=t!=null?i.indexOf(t[0]):i.length;if(o-l>1){const u=Math.round(.5*(l+o));return i[u]}else return t&&t.length>1?t.slice(0,1):i[l]+_r(n.slice(1),null,i)}function Gv(n){if(n.length!==Yv(n[0]))throw new Error(`invalid integer part of order key: `+n)}function Yv(n){if(n>=`a`&&n<=`z`)return n.charCodeAt(0)-97+2;if(n>=`A`&&n<=`Z`)return 90-n.charCodeAt(0)+2;throw new Error(`invalid order key head: `+n)}function Ja(n){const t=Yv(n[0]);if(t>n.length)throw new Error(`invalid order key: `+n);return n.slice(0,t)}function oS(n,t){if(n===`A`+t[0].repeat(26))throw new Error(`invalid order key: `+n);const i=Ja(n);if(n.slice(i.length).slice(-1)===t[0])throw new Error(`invalid order key: `+n)}function cS(n,t){Gv(n);const[i,...r]=n.split(``);let l=!0;for(let o=r.length-1;l&&o>=0;o--){const u=t.indexOf(r[o])+1;u===t.length?r[o]=t[0]:(r[o]=t[u],l=!1)}if(l){if(i===`Z`)return`a`+t[0];if(i===`z`)return null;const o=String.fromCharCode(i.charCodeAt(0)+1);return o>`a`?r.push(t[0]):r.pop(),o+r.join(``)}else return i+r.join(``)}function V_(n,t){Gv(n);const[i,...r]=n.split(``);let l=!0;for(let o=r.length-1;l&&o>=0;o--){const u=t.indexOf(r[o])-1;u===-1?r[o]=t.slice(-1):(r[o]=t[u],l=!1)}if(l){if(i===`a`)return`Z`+t.slice(-1);if(i===`A`)return null;const o=String.fromCharCode(i.charCodeAt(0)-1);return o<`Z`?r.push(t.slice(-1)):r.pop(),o+r.join(``)}else return i+r.join(``)}function $_(n,t,i=K_){if(n!=null&&oS(n,i),t!=null&&oS(t,i),n!=null&&t!=null&&n>=t)throw new Error(n+` >= `+t);if(n==null){if(t==null)return`a`+i[0];const p=Ja(t),g=t.slice(p.length);if(p===`A`+i[0].repeat(26))return p+_r(``,g,i);if(p{const o=n(i,l);return o!==0?o:gd(t,r)}}class ip{#t=[];#e;#n;#s;constructor(t,i,r){this.#n=t,this.#s=t+i,this.#e=r}get size(){const t=this.#n,i=this.#s-this.#n,r=this.#t.length-t;return Math.max(0,Math.min(i,r))}move({offset:t,limit:i}){const r=this.#n,l=this.#s-this.#n,o=[this.#n,this.#s===1/0?this.#n+this.size:this.#s];this.#n=t??r,this.#s=this.#n+(i??l);const u=[this.#n,this.#s===1/0?Math.max(this.#n+this.size,o[1]):this.#s],{onlyInA:d,onlyInB:p}=s_(o,u),g=[];p.forEach(m=>{const v=this.#t[m];v&&g.push(v)});const y=[];return d.forEach(m=>{const v=this.#t[m];v&&y.push(v)}),{moveIns:g,moveOuts:y,changes:d.length+p.length>0}}insert(t){const i={moveIn:null,moveOut:null},r=this.#a(t),l=r===0?null:hS(this.#t[r-1]),o=r===this.#t.length?null:hS(this.#t[r]),u=$_(l,o),d=uS(t,u);if(this.#t.splice(r,0,d),rthis.#e(fS(i),fS(r)))}}class Qv{#t=new Map;#e;constructor(t){this.#e=t}get size(){return this.#e.size}get isEmpty(){return this.#t.size===0&&this.#e.size===0}processElement(t,i,r){const{oldMultiplicity:l,newMultiplicity:o}=this.#n(t,r);return l<=0&&o>0?this.#e.insert([t,i]):l>0&&o<=0?this.#e.delete([t,i]):{moveIn:null,moveOut:null}}move(t){if(!(this.#e instanceof ip))throw new Error(`Cannot move B+-tree implementation of TopK with fractional index`);return this.#e.move(t)}#n(t,i){if(i===0){const o=this.#t.get(t)??0;return{oldMultiplicity:o,newMultiplicity:o}}const r=this.#t.get(t)??0,l=r+i;return l===0?this.#t.delete(t):this.#t.set(t,l),{oldMultiplicity:r,newMultiplicity:l}}}function bc(n,t){if(n){const[[i,r],l]=n;t.push([[i,[r,l]],1])}}function wc(n,t){if(n){const[[i,r],l]=n;t.push([[i,[r,l]],-1])}}class G_ extends Di{#t=new Map;#e;#n;#s;#a;constructor(t,i,r,l,o){super(t,i,r),this.#e=o.groupKeyFn,this.#a=o.limit??1/0,this.#s=o.offset??0,this.#n=Fv(l),o.setSizeCallback?.(()=>this.#i()),o.setWindowFn?.(this.#p.bind(this))}createTopK(t,i,r){return new ip(t,i,r)}#i(){let t=0;for(const i of this.#t.values())t+=i.size;return t}#c(t){let i=this.#t.get(t);if(!i){const r=this.createTopK(this.#s,this.#a,this.#n);i=new Qv(r),this.#t.set(t,i)}return i}#l(t,i){i.isEmpty&&this.#t.delete(t)}#p({offset:t,limit:i}){t!==void 0&&(this.#s=t),i!==void 0&&(this.#a=i);const r=[];let l=!1;for(const o of this.#t.values()){const u=o.move({offset:this.#s,limit:this.#a});u.moveIns.forEach(d=>bc(d,r)),u.moveOuts.forEach(d=>wc(d,r)),u.changes&&(l=!0)}l&&this.output.sendData(new ee(r))}run(){const t=[];for(const i of this.inputMessages())for(const[r,l]of i.getInner()){const[o,u]=r;this.#d(o,u,l,t)}t.length>0&&this.output.sendData(new ee(t))}#d(t,i,r,l){const o=this.#e(t,i),u=this.#c(o),d=u.processElement(t,i,r);bc(d.moveIn,l),wc(d.moveOut,l),this.#l(o,u)}}function Y_(n,t){return i=>{const r=new Dn(i.graph,new Rn),l=new G_(i.graph.getNextOperatorId(),i.connectReader(),r.writer,n,t);return i.graph.addOperator(l),r}}class F_ extends z_{#t=new Fs;#e=new Fs;#n;constructor(t,i,r,l,o=`inner`){super(t,i,r,l),this.#n=o}run(){const t=Fs.fromMultiSets(this.inputAMessages()),i=Fs.fromMultiSets(this.inputBMessages());if(t.size===0&&i.size===0)return;const r=new ee;this.#n!==`anti`&&this.emitInnerResults(t,i,r),(this.#n===`left`||this.#n===`full`||this.#n===`anti`)&&this.emitLeftOuterResults(t,i,r),(this.#n===`right`||this.#n===`full`)&&this.emitRightOuterResults(t,i,r),this.#t.append(t),this.#e.append(i),r.getInner().length>0&&this.output.sendData(r)}emitInnerResults(t,i,r){t.size>0&&r.extend(t.join(this.#e)),i.size>0&&r.extend(this.#t.join(i)),t.size>0&&i.size>0&&r.extend(t.join(i))}emitLeftOuterResults(t,i,r){if(t.size>0)for(const[l,o]of t.entriesIterators()){const u=this.#e.getConsolidatedMultiplicity(l),d=i.getConsolidatedMultiplicity(l);if(u+d===0)for(const[g,y]of o)y!==0&&r.add([l,[g,null]],y)}if(i.size>0)for(const l of i.getPresenceKeys()){const o=this.#e.getConsolidatedMultiplicity(l),u=i.getConsolidatedMultiplicity(l);if(u===0)continue;const d=o+u;if(o===0==(d===0))continue;const p=o===0;for(const[g,y]of this.#t.getIterator(l))y!==0&&r.add([l,[g,null]],p?-y:+y)}}emitRightOuterResults(t,i,r){if(i.size>0)for(const[l,o]of i.entriesIterators()){const u=this.#t.getConsolidatedMultiplicity(l),d=t.getConsolidatedMultiplicity(l);if(u+d===0)for(const[g,y]of o)y!==0&&r.add([l,[null,g]],y)}if(t.size>0)for(const l of t.getPresenceKeys()){const o=this.#t.getConsolidatedMultiplicity(l),u=t.getConsolidatedMultiplicity(l);if(u===0)continue;const d=o+u;if(o===0==(d===0))continue;const p=o===0;for(const[g,y]of this.#e.getIterator(l))y!==0&&r.add([l,[null,g]],p?-y:+y)}}}function Xv(n,t=`inner`){return i=>{if(i.graph!==n.graph)throw new Error(`Cannot join streams from different graphs`);const r=new Dn(i.graph,new Rn),l=new F_(i.graph.getNextOperatorId(),i.connectReader(),n.connectReader(),r.writer,t);return i.graph.addOperator(l),r}}class Q_ extends sp{#t;constructor(t,i,r,l){super(t,i,r),this.#t=l}inner(t){return t.map(this.#t)}}function le(n){return t=>{const i=new Dn(t.graph,new Rn),r=new Q_(t.graph.getNextOperatorId(),t.connectReader(),i.writer,n);return t.graph.addOperator(r),i}}class X_ extends Di{#t;constructor(t,i,r,l){super(t,i,r),this.#t=l}run(){for(const t of this.inputMessages())this.#t(t),this.output.sendData(t)}}function md(n){return t=>{const i=new Dn(t.graph,new Rn),r=new X_(t.graph.getNextOperatorId(),t.connectReader(),i.writer,n);return t.graph.addOperator(r),i}}class J_ extends sp{#t;constructor(t,i,r,l){super(t,i,r),this.#t=l}inner(t){return this.#t(t),t}}function Z_(n){return t=>{const i=new Dn(t.graph,new Rn),r=new J_(t.graph.getNextOperatorId(),t.connectReader(),i.writer,n);return t.graph.addOperator(r),i}}class W_ extends Di{#t;constructor(t,i,r,l,o){super(t,i,r);const u=o.limit??1/0,d=o.offset??0,p=this.createTopK(d,u,Fv(l));this.#t=new Qv(p),o.setSizeCallback?.(()=>this.#t.size),o.setWindowFn?.(this.moveTopK.bind(this))}createTopK(t,i,r){return new ip(t,i,r)}moveTopK({offset:t,limit:i}){const r=[],l=this.#t.move({offset:t,limit:i});l.moveIns.forEach(o=>bc(o,r)),l.moveOuts.forEach(o=>wc(o,r)),l.changes&&this.output.sendData(new ee(r))}run(){const t=[];for(const i of this.inputMessages())for(const[r,l]of i.getInner()){const[o,u]=r;this.processElement(o,u,l,t)}t.length>0&&this.output.sendData(new ee(t))}processElement(t,i,r,l){const o=this.#t.processElement(t,i,r);bc(o.moveIn,l),wc(o.moveOut,l)}}function P_(n,t){const i=t||{};return r=>{const l=new Dn(r.graph,new Rn),o=new W_(r.graph.getNextOperatorId(),r.connectReader(),l.writer,n,i);return r.graph.addOperator(o),l}}function dS(n){return`pipe`in n}function pS(n,t={}){const i=Object.fromEntries(Object.entries(t).filter(([r,l])=>!dS(l)));return Object.fromEntries(Object.entries(t).filter(([r,l])=>dS(l))),r=>{const l=`__original_key__`;return r.pipe(le(d=>{const p=n(d),g=cl(p),y={};y[l]=p;for(const[m,v]of Object.entries(i))y[m]=v.preMap(d);return[g,y]})).pipe($v(d=>{let p=0;for(const[m,v]of d)p+=v;if(p<=0)return[];const g={},y=d[0]?.[0]?.[l];g[l]=y;for(const[m,v]of Object.entries(i)){const w=d.map(([b,E])=>[b[m],E]);g[m]=v.reduce(w)}return[[g,1]]})).pipe(le(([d,p])=>{const g=p[l],y={};Object.assign(y,g);for(const[m,v]of Object.entries(i))v.postMap?y[m]=v.postMap(p[m]):y[m]=p[m];return[d,y]}))}}function tT(n=t=>t){return{preMap:t=>n(t),reduce:t=>{let i=0;for(const[r,l]of t)i+=r*l;return i}}}function eT(n=t=>t){return{preMap:t=>n(t)==null?0:1,reduce:t=>{let i=0;for(const[r,l]of t)i+=r*l;return i}}}function nT(n=t=>t){return{preMap:t=>({sum:n(t),count:0}),reduce:t=>{let i=0,r=0;for(const[l,o]of t)i+=l.sum*o,r+=o;return{sum:i,count:r}},postMap:t=>t.sum/t.count}}function sT(n){const t=n??(i=>i);return{preMap:i=>t(i),reduce:i=>{let r;for(const[l,o]of i)(!r||l&&li);return{preMap:i=>t(i),reduce:i=>{let r;for(const[l,o]of i)(!r||l&&l>r)&&(r=l);return r}}}const rT={sum:tT,count:eT,avg:nT,min:sT,max:iT};function aT(n,t){const i=t.limit??1/0,r=t.offset??0,l=t.setSizeCallback,o=t.setWindowFn,u=t.groupKeyFn,d=t.comparator??((p,g)=>p===g?0:pp.pipe(Y_((g,y)=>d(n(g),n(y)),{limit:i,offset:r,setSizeCallback:l,setWindowFn:o,groupKeyFn:u}),Vv())}function lT(n,t,i){const r=i?.limit??1/0,l=i?.offset??0,o=i?.setSizeCallback,u=i?.setWindowFn,d=i?.comparator??((p,g)=>p===g?0:pp.pipe(n((g,y)=>d(t(g),t(y)),{limit:r,offset:l,setSizeCallback:o,setWindowFn:u}),Vv())}function oT(n,t){return lT(P_,n,t)}const Bh=`__virtual_synced__`,Lh=`__virtual_has_local__`;function gS(n){let t=!1,i=!0,r=!1;for(const[l,o]of Object.entries(n)){if(l===`$selected`)continue;const u=o,d=`$synced`in u,p=`$origin`in u;!d&&!p||(t=!0,u.$synced===!1&&(i=!1),u.$origin===`local`&&(r=!0))}return{synced:t?i:!0,hasLocal:r}}const{sum:cT,count:uT,avg:fT,min:hT,max:dT}=rT;function pT(n,t){const i=new Map,r=[...n];if(!t)return{selectToGroupByIndex:i,groupByExpressions:r};for(const[l,o]of Object.entries(t)){if(o.type===`agg`||Lr(o))continue;const u=r.findIndex(d=>Ec(o,d));if(u===-1)throw new Ex(l);i.set(l,u)}return{selectToGroupByIndex:i,groupByExpressions:r}}function yS(n,t,i,r,l,o,u){const d={[Bh]:{preMap:([,b])=>gS(b).synced,reduce:b=>{for(const[E,_]of b)if(!E&&_>0)return!1;return!0}},[Lh]:{preMap:([,b])=>gS(b).hasLocal,reduce:b=>{for(const[E,_]of b)if(E&&_>0)return!0;return!1}}};if(t.length===0){const b=d,E={},_={value:0};if(r){for(const[O,A]of Object.entries(r))if(A.type===`agg`)b[O]=Jo(A);else if(Lr(A)){const{transformed:M,extracted:G}=Sd(A,_);for(const[q,K]of Object.entries(G))b[q]=Jo(K);E[O]=ue(M)}}const j=u?([,O])=>({__singleGroup:!0,__correlationKey:O?.[u]?.__correlationKey}):()=>({__singleGroup:!0});if(n=n.pipe(pS(j,b)),n=n.pipe(le(([,O])=>{const M={...O.$selected||{}};if(r){for(const[X,at]of Object.entries(r))at.type===`agg`&&(M[X]=O[X]);mS(M,O,E)}const G=u?O.__correlationKey:void 0,q=G!==void 0?`single_group_${cl(G)}`:`single_group`,K={...O,$selected:M},W=O[Bh],et=O[Lh];return K.$synced=W??!0,K.$origin=et?`local`:`remote`,K.$key=q,K.$collectionId=o??K.$collectionId,u&&G!==void 0&&(K[u]={__correlationKey:G}),[q,K]})),i&&i.length>0)for(const O of i){const A=J0(O),M=Cc(A,r||{},`$selected`),G=ue(M);n=n.pipe(ps(([,q])=>{const K={$selected:q.$selected};return Ar(G(K))}))}if(l&&l.length>0)for(const O of l)n=n.pipe(ps(([,A])=>{const M={$selected:A.$selected};return Ar(O(M))}));return n}const p=pT(t,r),g=t.map(b=>ue(b)),y=([,b])=>{const E={...b};delete E.$selected;const _={};for(let j=0;j{const E=b.$selected||{},_={};if(r){for(const[K,W]of Object.entries(r))if(W.type===`agg`)_[K]=b[K];else if(!v[K]){const et=p.selectToGroupByIndex.get(K);et!==void 0?_[K]=b[`__key_${et}`]:_[K]=E[K]}mS(_,b,v)}else for(let K=0;K0)for(const b of i){const E=J0(b),_=Cc(E,r||{}),j=ue(_);n=n.pipe(ps(([,O])=>{const A={$selected:O.$selected};return j(A)}))}if(l&&l.length>0)for(const b of l)n=n.pipe(ps(([,E])=>{const _={$selected:E.$selected};return Ar(b(_))}));return n}function Ec(n,t){if(!n||!t||n.type!==t.type)return!1;switch(n.type){case`ref`:return!n.path||!t.path||n.path.length!==t.path.length?!1:n.path.every((i,r)=>i===t.path[r]);case`val`:return n.value===t.value;case`func`:return n.name===t.name&&n.args?.length===t.args?.length&&(n.args||[]).every((i,r)=>Ec(i,t.args[r]));case`agg`:return n.name===t.name&&n.args?.length===t.args?.length&&(n.args||[]).every((i,r)=>Ec(i,t.args[r]));default:return!1}}function Jo(n){const t=ue(n.args[0]),i=([,o])=>{const u=t(o);return typeof u==`number`?u:u!=null?Number(u):0},r=([,o])=>{const u=t(o);return typeof u==`number`||typeof u==`string`||typeof u==`bigint`||u instanceof Date?u:u!=null?Number(u):0},l=([,o])=>t(o);switch(n.name.toLowerCase()){case`sum`:return cT(i);case`count`:return uT(l);case`avg`:return fT(i);case`min`:return hT(r);case`max`:return dT(r);default:throw new Cx(n.name)}}function Cc(n,t,i=`$selected`){switch(n.type){case`agg`:{const r=n;for(const[l,o]of Object.entries(t))if(o.type===`agg`&&gT(r,o))return new Oe([i,l]);throw new xx(r.name)}case`func`:{const r=n,l=r.args.map(o=>Cc(o,t));return new Ve(r.name,l)}case`ref`:return n;case`val`:return n;default:throw new _x(n.type)}}function mS(n,t,i){for(const r of Object.keys(t))r.startsWith(`__agg_`)&&(n[r]=t[r]);for(const[r,l]of Object.entries(i))n[r]=l({$selected:n});for(const r of Object.keys(n))r.startsWith(`__agg_`)&&delete n[r]}function Lr(n){return Br(n)?n.type===`agg`?!0:n.type===`func`&&`args`in n?n.args.some(t=>Lr(t)):!1:!1}function Sd(n,t){if(n.type===`agg`){const i=`__agg_${t.value++}`;return{transformed:new Oe([`$selected`,i]),extracted:{[i]:n}}}if(n.type===`func`){const i={},r=n.args.map(l=>{const o=Sd(l,t);return Object.assign(i,o.extracted),o.transformed});return{transformed:new Ve(n.name,r),extracted:i}}return{transformed:n,extracted:{}}}function gT(n,t){return n.name===t.name&&n.args.length===t.args.length&&n.args.every((i,r)=>Ec(i,t.args[r]))}function yT(n,t,i,r,l,o,u,d,p,g){const y=i.map(E=>{const _=Cc(E.expression,r,`$selected`);return{compiledExpression:ue(_),compareOptions:vd(E,l)}}),m=E=>{const _=E;return i.length>1?y.map(j=>j.compiledExpression(_)):i.length===1?y[0].compiledExpression(_):null},v=(E,_)=>{if(i.length>1){const j=E,O=_;for(let A=0;A1?String(M.path[0]):n.from.alias}}if(j){const q=i.every(X=>X.expression.type===`ref`)?i.map(X=>{const at=X.expression,nt=ol(n,at,l);return ue(nt?new Oe(nt.path):X.expression,!0)}):void 0;b={alias:O,offset:p??0,limit:d,comparator:(X,at)=>{if(i.length===1){const nt=X&&j(X),bt=at&&j(at);return v(nt,bt)}if(q){const nt=bt=>bt&&q.map(Lt=>Lt(bt));return v(nt(X),nt(at))}return 0},valueExtractorForRawRow:X=>{if(i.length===1)return j(X);if(q)return q.map(at=>at(X))},firstColumnValueExtractor:j,index:E,orderBy:i};const et=_?.id??l.id;o[et]=b,w=X=>{o[et].dataNeeded=()=>{const at=X();return Math.max(0,b.limit-at)}}}}return g?t.pipe(aT(m,{limit:d,offset:p,comparator:v,setSizeCallback:w,groupKeyFn:g,setWindowFn:E=>{u(_=>{E(_),b&&(b.offset=_.offset??b.offset,b.limit=_.limit??b.limit)})}})):t.pipe(oT(m,{limit:d,offset:p,comparator:v,setSizeCallback:w,setWindowFn:E=>{u(_=>{E(_),b&&(b.offset=_.offset??b.offset,b.limit=_.limit??b.limit)})}}))}function vd(n,t){return n.compareOptions.stringSort!==void 0?n.compareOptions:{...t.compareOptions,direction:n.compareOptions.direction,nulls:n.compareOptions.nulls}}function mT(n,t={}){const i=r=>{const l=[];for(const[o,u]of n.entries())(r?.(u)??!0)&&l.push({type:`insert`,key:o,value:u});return l};if(t.limit!==void 0&&!t.orderBy)throw new Error(`limit cannot be used without orderBy`);if(t.orderBy){const r=t.where?el(t.where):void 0,l=vT(n,t.orderBy,t.limit,r,t.optimizedOnly);if(l===void 0)return;const o=[];for(const u of l){const d=n.get(u);d!==void 0&&o.push({type:`insert`,key:u,value:d})}return o}if(!t.where)return i();try{const r=t.where,l=Yx(r,n);if(l.canOptimize){const o=[];for(const u of l.matchingKeys){const d=n.get(u);d!==void 0&&o.push({type:`insert`,key:u,value:d})}return o}else{if(t.optimizedOnly)return;const o=el(r);return i(o)}}catch(r){console.warn(`${n.id?`[${n.id}] `:``}Error processing where clause, falling back to full scan:`,r);const l=el(t.where);return t.optimizedOnly?void 0:i(l)}}function el(n){const t=Bv(n);return i=>{try{const r=t(i);return Ar(r)}catch{return!1}}}function ST(n,t){const i=el(t.whereExpression);return r=>{const l=[];for(const o of r)if(o.type===`insert`)i(o.value)&&l.push(o);else if(o.type===`update`){const u=i(o.value),d=o.previousValue?i(o.previousValue):!1;u&&d?l.push(o):u&&!d?l.push({...o,type:`insert`}):!u&&d&&l.push({...o,type:`delete`,value:o.previousValue})}else i(o.value)&&l.push(o);(l.length>0||r.length===0)&&n(l)}}function vT(n,t,i,r,l){if(t.length===1){const p=t[0],g=p.expression;if(g.type===`ref`){const m=g.path,v=vd(p,n);$c(m[0],m,n,v);const w=xl(n,m,v);if(w&&w.supports(`gt`)){const b=E=>{const _=n.get(E);return _===void 0?!1:r?.(_)??!0};return w.takeFromStart(i??w.keyCount,b)}}}if(l)return;const o=[];for(const[p,g]of n.entries())(r?.(g)??!0)&&o.push({key:p,value:g});const u=(p,g)=>{for(const y of t){const m=Pa(y.compareOptions),v=SS(p.value,y.expression),w=SS(g.value,y.expression),b=m(v,w);if(b!==0)return b}return 0};o.sort(u);const d=o.map(p=>p.key);return i!==void 0?d.slice(0,i):d}function SS(n,t){if(t.type===`ref`){const i=t;let r=n;for(const l of i.path)r=r?.[l];return r}else return t.type===`val`?t.value:Bv(t)(n)}class vS{constructor(t){this.map=new Map,this.sortedKeys=[],this.comparator=t}indexOf(t,i){let r=0,l=this.sortedKeys.length;if(!this.comparator){for(;r0)r=o+1;else return o}return r}for(;r0)r=o+1;else{const g=gd(t,u);if(g<0)l=o;else if(g>0)r=o+1;else return o}}return r}set(t,i){if(this.map.has(t)){const l=this.map.get(t),o=this.indexOf(t,l);this.sortedKeys.splice(o,1)}const r=this.indexOf(t,i);return this.sortedKeys.splice(r,0,t),this.map.set(t,i),this}get(t){return this.map.get(t)}delete(t){if(this.map.has(t)){const i=this.map.get(t),r=this.indexOf(t,i);return this.sortedKeys.splice(r,1),this.map.delete(t)}return!1}has(t){return this.map.has(t)}clear(){this.map.clear(),this.sortedKeys=[]}get size(){return this.map.size}*[Symbol.iterator](){for(const t of this.sortedKeys)yield[t,this.map.get(t)]}entries(){return this[Symbol.iterator]()}keys(){return this.sortedKeys[Symbol.iterator]()}values(){return(function*(){for(const t of this.sortedKeys)yield this.map.get(t)}).call(this)}forEach(t){for(const i of this.sortedKeys)t(this.map.get(i),i,this.map)}}const lc=`__tanstack_db_direct`;class bT{constructor(t){this.pendingSyncedTransactions=[],this.syncedMetadata=new Map,this.syncedCollectionMetadata=new Map,this.optimisticUpserts=new Map,this.optimisticDeletes=new Set,this.pendingOptimisticUpserts=new Map,this.pendingOptimisticDeletes=new Set,this.pendingOptimisticDirectUpserts=new Set,this.pendingOptimisticDirectDeletes=new Set,this.rowOrigins=new Map,this.pendingLocalChanges=new Set,this.pendingLocalOrigins=new Set,this.virtualPropsCache=new WeakMap,this.size=0,this.syncedKeys=new Set,this.preSyncVisibleState=new Map,this.recentlySyncedKeys=new Set,this.hasReceivedFirstCommit=!1,this.isCommittingSyncTransactions=!1,this.isLocalOnly=!1,this.commitPendingTransactions=()=>{let i=!1;for(const d of this.transactions.values())if(d.state===`persisting`){i=!0;break}const{committedSyncedTransactions:r,uncommittedSyncedTransactions:l,hasTruncateSync:o,hasImmediateSync:u}=this.pendingSyncedTransactions.reduce((d,p)=>(p.committed?(d.committedSyncedTransactions.push(p),p.truncate&&(d.hasTruncateSync=!0),p.immediate&&(d.hasImmediateSync=!0)):d.uncommittedSyncedTransactions.push(p),d),{committedSyncedTransactions:[],uncommittedSyncedTransactions:[],hasTruncateSync:!1,hasImmediateSync:!1});if(!i||o||u){this.isCommittingSyncTransactions=!0;const d=new Map(this.rowOrigins),p=new Map(this.optimisticUpserts),g=new Set(this.optimisticDeletes),y=o?r.find(O=>O.truncate)?.optimisticSnapshot:null;let m,v;const w=new Set;for(const O of r){for(const A of O.operations)w.add(A.key);for(const[A]of O.rowMetadataWrites)w.add(A)}let b=this.preSyncVisibleState;if(b.size===0){b=new Map;for(const O of w){const A=this.get(O);A!==void 0&&b.set(O,A)}}const E=[],_=this.config.sync.rowUpdateMode||`partial`,j=new Map;for(const O of this.transactions.values())if(O.state===`completed`)for(const A of O.mutations)this.isThisCollection(A.collection)&&A.optimistic&&j.set(A.key,{type:A.type,value:A.modified});for(const O of r){if(O.truncate){const A=new Set([...this.syncedData.keys(),...y?.upserts.keys()||[]]);for(const M of A){if(y?.deletes.has(M))continue;const G=y?.upserts.get(M)||this.syncedData.get(M);G!==void 0&&E.push({type:`delete`,key:M,value:G})}m=new Set(this.pendingLocalChanges),v=new Set(this.pendingLocalOrigins),this.syncedData.clear(),this.syncedMetadata.clear(),this.syncedKeys.clear(),this.clearOriginTrackingState();for(const M of w)b.delete(M);this._events.emit(`truncate`,{type:`truncate`,collection:this.collection})}for(const A of O.operations){const M=A.key;this.syncedKeys.add(M);const G=this.isLocalOnly||this.pendingLocalChanges.has(M)||this.pendingLocalOrigins.has(M)||m?.has(M)===!0||v?.has(M)===!0?`local`:`remote`;switch(A.type){case`insert`:this.syncedData.set(M,A.value),this.rowOrigins.set(M,G),this.pendingLocalChanges.delete(M),this.pendingLocalOrigins.delete(M),this.pendingOptimisticUpserts.delete(M),this.pendingOptimisticDeletes.delete(M),this.pendingOptimisticDirectUpserts.delete(M),this.pendingOptimisticDirectDeletes.delete(M);break;case`update`:{if(_===`partial`){const q=Object.assign({},this.syncedData.get(M),A.value);this.syncedData.set(M,q)}else this.syncedData.set(M,A.value);this.rowOrigins.set(M,G),this.pendingLocalChanges.delete(M),this.pendingLocalOrigins.delete(M),this.pendingOptimisticUpserts.delete(M),this.pendingOptimisticDeletes.delete(M),this.pendingOptimisticDirectUpserts.delete(M),this.pendingOptimisticDirectDeletes.delete(M);break}case`delete`:this.syncedData.delete(M),this.syncedMetadata.delete(M),this.rowOrigins.delete(M),this.pendingLocalChanges.delete(M),this.pendingLocalOrigins.delete(M),this.pendingOptimisticUpserts.delete(M),this.pendingOptimisticDeletes.delete(M),this.pendingOptimisticDirectUpserts.delete(M),this.pendingOptimisticDirectDeletes.delete(M);break}}for(const[A,M]of O.rowMetadataWrites){if(M.type===`delete`){this.syncedMetadata.delete(A);continue}this.syncedMetadata.set(A,M.value)}for(const[A,M]of O.collectionMetadataWrites){if(M.type===`delete`){this.syncedCollectionMetadata.delete(A);continue}this.syncedCollectionMetadata.set(A,M.value)}}if(o){const O=new Set;for(const G of r)for(const q of G.operations)(q.type===`insert`||q.type===`update`)&&O.add(q.key);const A=new Map(y.upserts),M=new Set(y.deletes);for(const[G,q]of A)if(!M.has(G))if(O.has(G)){let K=!1;for(let W=E.length-1;W>=0;W--){const et=E[W];if(et.key===G&&et.type===`insert`){et.value=q,K=!0;break}}K||E.push({type:`insert`,key:G,value:q})}else E.push({type:`insert`,key:G,value:q});if(E.length>0&&M.size>0){const G=[];for(const q of E)q.type===`insert`&&M.has(q.key)||G.push(q);E.length=0,E.push(...G)}this.lifecycle.status!==`ready`&&this.lifecycle.markReady()}if(this.optimisticUpserts.clear(),this.optimisticDeletes.clear(),this.isCommittingSyncTransactions=!1,o&&y){for(const[O,A]of y.upserts)this.optimisticUpserts.set(O,A);for(const O of y.deletes)this.optimisticDeletes.add(O)}for(const O of this.transactions.values())if(![`completed`,`failed`].includes(O.state)){for(const A of O.mutations)if(this.isThisCollection(A.collection)&&A.optimistic)switch(A.type){case`insert`:case`update`:this.optimisticUpserts.set(A.key,A.modified),this.optimisticDeletes.delete(A.key);break;case`delete`:this.optimisticUpserts.delete(A.key),this.optimisticDeletes.add(A.key);break}}for(const O of w){const A=b.get(O),M=this.get(O),G=this.getVirtualPropsSnapshotForState(O,{rowOrigins:d,optimisticUpserts:p,optimisticDeletes:g,completedOptimisticKeys:j}),q=this.getVirtualPropsSnapshotForState(O),K=G.$synced!==q.$synced||G.$origin!==q.$origin,W=A!==void 0?rS(A,O,this.collection.id,()=>G.$synced,()=>G.$origin):void 0,et=j.get(O);let X=!1;et&&(et.type===`delete`&&A!==void 0&&M===void 0&&Bn(et.value,A)||M!==void 0&&Bn(et.value,M))&&(X=!0);const at=K&&A!==void 0&&M!==void 0&&Bn(A,M);if(!(X&&!at))if(A===void 0&&M!==void 0){const nt=j.get(O);if(nt){const bt=nt.value,Lt=rS(bt,O,this.collection.id,()=>G.$synced,()=>G.$origin);E.push({type:`update`,key:O,value:M,previousValue:Lt})}else E.push({type:`insert`,key:O,value:M})}else A!==void 0&&M===void 0?E.push({type:`delete`,key:O,value:W??A}):A!==void 0&&M!==void 0&&(!Bn(A,M)||at)&&E.push({type:`update`,key:O,value:M,previousValue:W??A})}this.size=this.calculateSize(),E.length>0&&this.indexes.updateIndexes(E),this.changes.emitEvents(E,!0),this.pendingSyncedTransactions=l,this.preSyncVisibleState.clear(),Promise.resolve().then(()=>{this.recentlySyncedKeys.clear()}),this.hasReceivedFirstCommit||(this.hasReceivedFirstCommit=!0)}},this.config=t,this.transactions=new vS((i,r)=>i.compareCreatedAt(r)),this.syncedData=new vS(t.compare)}setDeps(t){this.collection=t.collection,this.lifecycle=t.lifecycle,this.changes=t.changes,this.indexes=t.indexes,this._events=t.events}isRowSynced(t){return this.isLocalOnly?!0:!this.optimisticUpserts.has(t)&&!this.optimisticDeletes.has(t)}getRowOrigin(t){return this.isLocalOnly||this.optimisticUpserts.has(t)||this.optimisticDeletes.has(t)?`local`:this.rowOrigins.get(t)??`remote`}createVirtualPropsSnapshot(t,i){return{$synced:i?.$synced??this.isRowSynced(t),$origin:i?.$origin??this.getRowOrigin(t),$key:i?.$key??t,$collectionId:i?.$collectionId??this.collection.id}}getVirtualPropsSnapshotForState(t,i){if(this.isLocalOnly)return this.createVirtualPropsSnapshot(t,{$synced:!0,$origin:`local`});const r=i?.optimisticUpserts??this.optimisticUpserts,l=i?.optimisticDeletes??this.optimisticDeletes,o=r.has(t)||l.has(t)||i?.completedOptimisticKeys?.has(t)===!0;return this.createVirtualPropsSnapshot(t,{$synced:!o,$origin:o?`local`:(i?.rowOrigins??this.rowOrigins).get(t)??`remote`})}enrichWithVirtualPropsSnapshot(t,i){const r=t,l=r.$synced??i.$synced,o=r.$origin??i.$origin,u=r.$key??i.$key,d=r.$collectionId??i.$collectionId,p=this.virtualPropsCache.get(t);if(p&&p.synced===l&&p.origin===o&&p.key===u&&p.collectionId===d)return p.enriched;const g={...t,$synced:l,$origin:o,$key:u,$collectionId:d};return this.virtualPropsCache.set(t,{synced:l,origin:o,key:u,collectionId:d,enriched:g}),g}clearOriginTrackingState(){this.rowOrigins.clear(),this.pendingLocalChanges.clear(),this.pendingLocalOrigins.clear()}enrichWithVirtualProps(t,i){return this.enrichWithVirtualPropsSnapshot(t,this.createVirtualPropsSnapshot(i))}enrichChangeMessage(t){const{__virtualProps:i}=t,r=i?.value?this.enrichWithVirtualPropsSnapshot(t.value,i.value):this.enrichWithVirtualProps(t.value,t.key),l=t.previousValue?i?.previousValue?this.enrichWithVirtualPropsSnapshot(t.previousValue,i.previousValue):this.enrichWithVirtualProps(t.previousValue,t.key):void 0;return{key:t.key,type:t.type,value:r,previousValue:l,metadata:t.metadata}}getWithVirtualProps(t){const i=this.get(t);if(i!==void 0)return this.enrichWithVirtualProps(i,t)}get(t){const{optimisticDeletes:i,optimisticUpserts:r,syncedData:l}=this;if(!i.has(t))return r.has(t)?r.get(t):l.get(t)}has(t){const{optimisticDeletes:i,optimisticUpserts:r,syncedData:l}=this;return i.has(t)?!1:r.has(t)?!0:l.has(t)}*keys(){const{syncedData:t,optimisticDeletes:i,optimisticUpserts:r}=this;for(const l of t.keys())i.has(l)||(yield l);for(const l of r.keys())!t.has(l)&&!i.has(l)&&(yield l)}*values(){for(const t of this.keys()){const i=this.get(t);i!==void 0&&(yield i)}}*entries(){for(const t of this.keys()){const i=this.get(t);i!==void 0&&(yield[t,i])}}*[Symbol.iterator](){for(const[t,i]of this.entries())yield[t,i]}forEach(t){let i=0;for(const[r,l]of this.entries())t(l,r,i++)}map(t){const i=[];let r=0;for(const[l,o]of this.entries())i.push(t(o,l,r++));return i}isThisCollection(t){return t===this.collection}recomputeOptimisticState(t=!1){if(this.isCommittingSyncTransactions&&!t)return;const i=new Map(this.optimisticUpserts),r=new Set(this.optimisticDeletes),l=new Map(this.rowOrigins);for(const m of this.transactions.values()){const v=m.metadata[lc]===!0;if(m.state===`completed`){for(const w of m.mutations)if(this.isThisCollection(w.collection)&&(this.pendingLocalOrigins.add(w.key),!!w.optimistic))switch(w.type){case`insert`:case`update`:this.pendingOptimisticUpserts.set(w.key,w.modified),this.pendingOptimisticDeletes.delete(w.key),v?(this.pendingOptimisticDirectUpserts.add(w.key),this.pendingOptimisticDirectDeletes.delete(w.key)):(this.pendingOptimisticDirectUpserts.delete(w.key),this.pendingOptimisticDirectDeletes.delete(w.key));break;case`delete`:this.pendingOptimisticUpserts.delete(w.key),this.pendingOptimisticDeletes.add(w.key),v?(this.pendingOptimisticDirectUpserts.delete(w.key),this.pendingOptimisticDirectDeletes.add(w.key)):(this.pendingOptimisticDirectUpserts.delete(w.key),this.pendingOptimisticDirectDeletes.delete(w.key));break}}else if(m.state===`failed`)for(const w of m.mutations)this.isThisCollection(w.collection)&&(this.pendingLocalOrigins.delete(w.key),w.optimistic&&(this.pendingOptimisticUpserts.delete(w.key),this.pendingOptimisticDeletes.delete(w.key),this.pendingOptimisticDirectUpserts.delete(w.key),this.pendingOptimisticDirectDeletes.delete(w.key)))}this.optimisticUpserts.clear(),this.optimisticDeletes.clear(),this.pendingLocalChanges.clear();const o=new Set;for(const m of this.pendingSyncedTransactions)for(const v of m.operations)o.add(v.key);const u=[];for(const[m,v]of this.pendingOptimisticUpserts)o.has(m)||this.pendingOptimisticDirectUpserts.has(m)?this.optimisticUpserts.set(m,v):u.push(m);for(const m of u)this.pendingOptimisticUpserts.delete(m),this.pendingLocalOrigins.delete(m);const d=[];for(const m of this.pendingOptimisticDeletes)o.has(m)||this.pendingOptimisticDirectDeletes.has(m)?this.optimisticDeletes.add(m):d.push(m);for(const m of d)this.pendingOptimisticDeletes.delete(m),this.pendingLocalOrigins.delete(m);const p=[];for(const m of this.transactions.values())[`completed`,`failed`].includes(m.state)||p.push(m);for(const m of p)for(const v of m.mutations)if(this.isThisCollection(v.collection)&&(this.pendingLocalChanges.add(v.key),v.optimistic))switch(v.type){case`insert`:case`update`:this.optimisticUpserts.set(v.key,v.modified),this.optimisticDeletes.delete(v.key);break;case`delete`:this.optimisticUpserts.delete(v.key),this.optimisticDeletes.add(v.key);break}this.size=this.calculateSize();const g=[];this.collectOptimisticChanges(i,r,l,g);const y=g.filter(m=>!!(!this.recentlySyncedKeys.has(m.key)||t));if(this.pendingSyncedTransactions.length>0&&!t){const m=new Set;for(const w of this.pendingSyncedTransactions)for(const b of w.operations)m.add(b.key);const v=y.filter(w=>!(w.type===`delete`&&m.has(w.key)&&!p.some(E=>E.mutations.some(_=>this.isThisCollection(_.collection)&&_.key===w.key))));v.length>0&&this.indexes.updateIndexes(v),this.changes.emitEvents(v,t)}else y.length>0&&this.indexes.updateIndexes(y),this.changes.emitEvents(y,t)}calculateSize(){const t=this.syncedData.size,i=Array.from(this.optimisticDeletes).filter(l=>this.syncedData.has(l)&&!this.optimisticUpserts.has(l)).length,r=Array.from(this.optimisticUpserts.keys()).filter(l=>!this.syncedData.has(l)).length;return t-i+r}collectOptimisticChanges(t,i,r,l){const o=new Set([...t.keys(),...this.optimisticUpserts.keys(),...i,...this.optimisticDeletes]);for(const u of o){const d=this.get(u),p=this.getPreviousValue(u,t,i),g=this.getVirtualPropsSnapshotForState(u,{rowOrigins:r,optimisticUpserts:t,optimisticDeletes:i}),y=this.getVirtualPropsSnapshotForState(u);p!==void 0&&d===void 0?l.push({type:`delete`,key:u,value:p,__virtualProps:{value:g}}):p===void 0&&d!==void 0?l.push({type:`insert`,key:u,value:d,__virtualProps:{value:y}}):p!==void 0&&d!==void 0&&p!==d&&l.push({type:`update`,key:u,value:d,previousValue:p,__virtualProps:{value:y,previousValue:g}})}}getPreviousValue(t,i,r){if(!r.has(t))return i.has(t)?i.get(t):this.syncedData.get(t)}scheduleTransactionCleanup(t){if(t.state===`completed`){this.transactions.delete(t.id);return}t.isPersisted.promise.then(()=>{this.transactions.delete(t.id)}).catch(()=>{})}capturePreSyncVisibleState(){if(this.pendingSyncedTransactions.length===0)return;const t=new Set;for(const i of this.pendingSyncedTransactions)for(const r of i.operations)t.add(r.key);for(const i of t)this.recentlySyncedKeys.add(i);for(const i of t)if(!this.preSyncVisibleState.has(i)){const r=this.get(i);r!==void 0&&this.preSyncVisibleState.set(i,r)}}onTransactionStateChange(){this.changes.shouldBatchEvents=this.pendingSyncedTransactions.length>0,this.capturePreSyncVisibleState(),this.recomputeOptimisticState(!1)}cleanup(){this.syncedData.clear(),this.syncedMetadata.clear(),this.syncedCollectionMetadata.clear(),this.optimisticUpserts.clear(),this.optimisticDeletes.clear(),this.pendingOptimisticUpserts.clear(),this.pendingOptimisticDeletes.clear(),this.pendingOptimisticDirectUpserts.clear(),this.pendingOptimisticDirectDeletes.clear(),this.clearOriginTrackingState(),this.isLocalOnly=!1,this.size=0,this.pendingSyncedTransactions=[],this.syncedKeys.clear(),this.hasReceivedFirstCommit=!1}}function Jv(){const n=new Map;function t(i){const r=i.join(`.`);if(n.has(r))return n.get(r);const l=new Proxy({},{get(o,u,d){if(u===`__refProxy`)return!0;if(u===`__path`)return i;if(u===`__type`)return;if(typeof u==`symbol`)return Reflect.get(o,u,d);const p=[...i,String(u)];return t(p)},has(o,u){return u===`__refProxy`||u===`__path`||u===`__type`?!0:Reflect.has(o,u)},ownKeys(o){return Reflect.ownKeys(o)},getOwnPropertyDescriptor(o,u){return u===`__refProxy`||u===`__path`||u===`__type`?{enumerable:!1,configurable:!0}:Reflect.getOwnPropertyDescriptor(o,u)}});return n.set(r,l),l}return t([])}function vi(n){const t=new Map;let i=0;function r(o){const u=o.join(`.`);if(t.has(u))return t.get(u);const d=new Proxy({},{get(p,g,y){if(g===`__refProxy`)return!0;if(g===`__path`)return o;if(g===`__type`)return;if(typeof g==`symbol`)return Reflect.get(p,g,y);const m=[...o,String(g)];return r(m)},has(p,g){return g===`__refProxy`||g===`__path`||g===`__type`?!0:Reflect.has(p,g)},ownKeys(p){const g=++i,y=`__SPREAD_SENTINEL__${o.join(`.`)}__${g}`;return Object.prototype.hasOwnProperty.call(p,y)||Object.defineProperty(p,y,{enumerable:!0,configurable:!0,value:!0}),Reflect.ownKeys(p)},getOwnPropertyDescriptor(p,g){return g===`__refProxy`||g===`__path`||g===`__type`?{enumerable:!1,configurable:!0}:Reflect.getOwnPropertyDescriptor(p,g)}});return t.set(u,d),d}return new Proxy({},{get(o,u,d){if(u===`__refProxy`)return!0;if(u===`__path`)return[];if(u===`__type`)return;if(typeof u==`symbol`)return Reflect.get(o,u,d);const p=String(u);if(n.includes(p))return r([p])},has(o,u){return u===`__refProxy`||u===`__path`||u===`__type`||typeof u==`string`&&n.includes(u)?!0:Reflect.has(o,u)},ownKeys(o){return[...n,`__refProxy`,`__path`,`__type`]},getOwnPropertyDescriptor(o,u){if(u===`__refProxy`||u===`__path`||u===`__type`)return{enumerable:!1,configurable:!0};if(typeof u==`string`&&n.includes(u))return{enumerable:!0,configurable:!0}}})}function bS(n){const t=vi(n),i=new Map;function r(o){const u=o.join(`.`);if(i.has(u))return i.get(u);const d=new Proxy({},{get(p,g,y){if(g===`__refProxy`)return!0;if(g===`__path`)return[`$selected`,...o];if(g===`__type`)return;if(typeof g==`symbol`)return Reflect.get(p,g,y);const m=[...o,String(g)];return r(m)},has(p,g){return g===`__refProxy`||g===`__path`||g===`__type`?!0:Reflect.has(p,g)},ownKeys(p){return Reflect.ownKeys(p)},getOwnPropertyDescriptor(p,g){return g===`__refProxy`||g===`__path`||g===`__type`?{enumerable:!1,configurable:!0}:Reflect.getOwnPropertyDescriptor(p,g)}});return i.set(u,d),d}const l=r([]);return new Proxy(t,{get(o,u,d){return u===`$selected`?l:Reflect.get(o,u,d)},has(o,u){return u===`$selected`?!0:Reflect.has(o,u)},ownKeys(o){return[...Reflect.ownKeys(o),`$selected`]},getOwnPropertyDescriptor(o,u){return u===`$selected`?{enumerable:!0,configurable:!0,value:l}:Reflect.getOwnPropertyDescriptor(o,u)}})}function ne(n){return oc(n)?new Oe(n.__path):n&&typeof n==`object`&&`type`in n&&(n.type===`func`||n.type===`ref`||n.type===`val`||n.type===`agg`)?n:new Ue(n)}function oc(n){return n&&typeof n==`object`&&n.__refProxy===!0}function bd(n,t){return new Ve(`eq`,[ne(n),ne(t)])}function wd(n,t){return new Ve(`gt`,[ne(n),ne(t)])}function wT(n,t){return new Ve(`gte`,[ne(n),ne(t)])}function Ed(n,t){return new Ve(`lt`,[ne(n),ne(t)])}function Cd(n,t,...i){const r=[n,t,...i];return new Ve(`and`,r.map(l=>ne(l)))}function ET(n,t,...i){const r=[n,t,...i];return new Ve(`or`,r.map(l=>ne(l)))}function CT(n,t){return new Ve(`in`,[ne(n),ne(t)])}class xT{constructor(t){this.query=t}}class _T{constructor(t){this.query=t}}class Zv{constructor(){this.listeners=new Map}on(t,i){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(i),()=>{this.listeners.get(t)?.delete(i)}}once(t,i){const r=this.on(t,l=>{i(l),r()});return r}off(t,i){this.listeners.get(t)?.delete(i)}waitFor(t,i){return new Promise((r,l)=>{let o;const u=this.on(t,d=>{o&&(clearTimeout(o),o=void 0),r(d),u()});i&&(o=setTimeout(()=>{o=void 0,u(),l(new Error(`Timeout waiting for event ${String(t)}`))},i))})}emitInner(t,i){this.listeners.get(t)?.forEach(r=>{try{r(i)}catch(l){queueMicrotask(()=>{throw l})}})}clearListeners(){this.listeners.clear()}}function TT(n,t){if(t.length===0||n.length===0)return;if(n.length===1){const{expression:r,compareOptions:l}=n[0];return(l.direction===`asc`?wd:Ed)(r,new Ue(t[0]))}const i=[];for(let r=0;rCd(y,m)))}}return i.length===1?i[0]:i.reduce((r,l)=>ET(r,l))}class AT extends Zv{constructor(t,i,r){super(),this.collection=t,this.callback=i,this.options=r,this.loadedInitialState=!1,this.skipFiltering=!1,this.snapshotSent=!1,this.loadedSubsets=[],this.sentKeys=new Set,this.limitedSnapshotRowCount=0,this._status=`ready`,this.pendingLoadSubsetPromises=new Set,this.isBufferingForTruncate=!1,this.truncateBuffer=[],this.pendingTruncateRefetches=new Set,r.onUnsubscribe&&this.on(`unsubscribed`,o=>r.onUnsubscribe(o)),r.whereExpression&&Wx(r.whereExpression,this.collection);const l=o=>{i(o),this.trackSentKeys(o)};this.callback=l,this.filteredCallback=r.whereExpression?ST(this.callback,r):this.callback,this.truncateCleanup=this.collection.on(`truncate`,()=>{this.handleTruncate()})}get status(){return this._status}handleTruncate(){const t=[...this.loadedSubsets],i=this.collection._sync.syncLoadSubsetFn!==null;if(t.length===0||!i){this.snapshotSent=!1,this.loadedInitialState=!1,this.limitedSnapshotRowCount=0,this.lastSentKey=void 0,this.loadedSubsets=[];return}this.isBufferingForTruncate=!0,this.truncateBuffer=[],this.pendingTruncateRefetches.clear(),this.snapshotSent=!1,this.loadedInitialState=!1,this.limitedSnapshotRowCount=0,this.lastSentKey=void 0,this.loadedSubsets=[],queueMicrotask(()=>{if(this.isBufferingForTruncate){for(const r of t){const l=this.collection._sync.loadSubset(r);this.loadedSubsets.push(r),this.trackLoadSubsetPromise(l),l instanceof Promise&&(this.pendingTruncateRefetches.add(l),l.catch(()=>{}).finally(()=>{this.pendingTruncateRefetches.delete(l),this.checkTruncateRefetchComplete()}))}this.pendingTruncateRefetches.size===0&&this.flushTruncateBuffer()}})}checkTruncateRefetchComplete(){this.pendingTruncateRefetches.size===0&&this.isBufferingForTruncate&&this.flushTruncateBuffer()}flushTruncateBuffer(){this.isBufferingForTruncate=!1;const t=this.truncateBuffer.flat();t.length>0&&this.filteredCallback(t),this.truncateBuffer=[]}setOrderByIndex(t){this.orderByIndex=t}hasOrderByIndex(){return this.orderByIndex!==void 0}setStatus(t){if(this._status===t)return;const i=this._status;this._status=t,this.emitInner(`status:change`,{type:`status:change`,subscription:this,previousStatus:i,status:t});const r=`status:${t}`;this.emitInner(r,{type:r,subscription:this,previousStatus:i,status:t})}trackLoadSubsetPromise(t){t instanceof Promise&&(this.pendingLoadSubsetPromises.add(t),this.setStatus(`loadingSubset`),t.finally(()=>{this.pendingLoadSubsetPromises.delete(t),this.pendingLoadSubsetPromises.size===0&&this.setStatus(`ready`)}))}hasLoadedInitialState(){return this.loadedInitialState}hasSentAtLeastOneSnapshot(){return this.snapshotSent}emitEvents(t){const i=this.filterAndFlipChanges(t);this.isBufferingForTruncate?i.length>0&&this.truncateBuffer.push(i):this.filteredCallback(i)}requestSnapshot(t){if(this.loadedInitialState)return!1;const i={where:this.options.whereExpression,optimizedOnly:t?.optimizedOnly??!1};if(t){if(`where`in t){const p=t.where;if(i.where){const g=i.where,y=Cd(g,p);i.where=y}else i.where=p}}else this.loadedInitialState=!0;const r={where:i.where,subscription:this,orderBy:t?.orderBy,limit:t?.limit},l=this.collection._sync.loadSubset(r);t?.onLoadSubsetResult?.(l),this.loadedSubsets.push(r),(t?.trackLoadSubsetPromise??!0)&&this.trackLoadSubsetPromise(l);const u=this.collection.currentStateAsChanges(i);if(u===void 0)return!1;const d=u.filter(p=>!this.sentKeys.has(p.key));for(const p of d)this.sentKeys.add(p.key);return this.snapshotSent=!0,this.callback(d),!0}requestLimitedSnapshot({orderBy:t,limit:i,minValues:r,offset:l,trackLoadSubsetPromise:o=!0,onLoadSubsetResult:u}){if(!i)throw new Error(`limit is required`);if(!this.orderByIndex)throw new Error(`Ordered snapshot was requested but no index was found. You have to call setOrderByIndex before requesting an ordered snapshot.`);const d=r!==void 0&&r.length>0,g=r?.[0],y=this.orderByIndex,m=this.options.whereExpression,v=m?el(m):void 0,w=et=>{if(et!==void 0&&this.sentKeys.has(et))return!1;const X=this.collection.get(et);return X===void 0?!1:v?.(X)??!0};let b=g;const E=[];let _=[];if(d){const{expression:et}=t[0],X=this.collection.currentStateAsChanges({where:bd(et,new Ue(g))});if(X){const at=X.map(bt=>bt.key).filter(bt=>!this.sentKeys.has(bt)&&w(bt));_.push(...at);const nt=y.take(i-_.length,g,w);_.push(...nt)}else _=y.take(i,g,w)}else _=y.takeFromStart(i,w);const j=()=>Math.max(i-E.length,0),O=()=>_.length===0,A=t[0].expression,M=A.type===`ref`?ue(new Oe(A.path),!0):null;for(;j()>0&&!O();){const et=new Set;for(const X of _){const at=this.collection.get(X);E.push({type:`insert`,key:X,value:at}),b=M?M(at):at,et.add(X)}_=y.take(j(),b,w)}const G=this.limitedSnapshotRowCount;for(const et of E)this.sentKeys.add(et.key);this.callback(E),this.limitedSnapshotRowCount+=E.length,E.length>0&&(this.lastSentKey=E[E.length-1].key);let q;if(r!==void 0&&r.length>0){const et=TT(t,r);if(et){const{expression:X}=t[0],at=r[0];let nt;if(at instanceof Date){const bt=new Date(at.getTime()+1);nt=Cd(wT(X,new Ue(at)),Ed(X,new Ue(bt)))}else nt=bd(X,new Ue(at));q={whereFrom:et,whereCurrent:nt,lastKey:this.lastSentKey}}}const K={where:m,limit:i,orderBy:t,cursor:q,offset:l??G,subscription:this},W=this.collection._sync.loadSubset(K);u?.(W),this.loadedSubsets.push(K),o&&this.trackLoadSubsetPromise(W)}filterAndFlipChanges(t){if(this.loadedInitialState||this.skipFiltering)return t;const i=this.isBufferingForTruncate,r=[];for(const l of t){let o=l;if(this.sentKeys.has(l.key)){if(l.type===`insert`)continue;l.type===`delete`&&this.sentKeys.delete(l.key)}else{if(l.type===`update`)o={...l,type:`insert`,previousValue:void 0};else if(l.type===`delete`&&!i)continue;this.sentKeys.add(l.key)}r.push(o)}return r}trackSentKeys(t){if(!(this.loadedInitialState||this.skipFiltering)){for(const i of t)i.type===`delete`?this.sentKeys.delete(i.key):this.sentKeys.add(i.key);this.orderByIndex&&(this.limitedSnapshotRowCount=Math.max(this.limitedSnapshotRowCount,this.sentKeys.size))}}markAllStateAsSeen(){this.skipFiltering=!0}unsubscribe(){this.truncateCleanup?.(),this.truncateCleanup=void 0,this.isBufferingForTruncate=!1,this.truncateBuffer=[],this.pendingTruncateRefetches.clear();for(const t of this.loadedSubsets)this.collection._sync.unloadSubset(t);this.loadedSubsets=[],this.emitInner(`unsubscribed`,{type:`unsubscribed`,subscription:this}),this.clearListeners()}}class OT{constructor(){this.activeSubscribersCount=0,this.changeSubscriptions=new Set,this.batchedEvents=[],this.shouldBatchEvents=!1}setDeps(t){this.lifecycle=t.lifecycle,this.sync=t.sync,this.events=t.events,this.collection=t.collection,this.state=t.state}emitEmptyReadyEvent(){for(const t of this.changeSubscriptions)t.emitEvents([])}enrichChangeWithVirtualProps(t){return this.state.enrichChangeMessage(t)}emitEvents(t,i=!1){if(this.shouldBatchEvents&&!i){this.batchedEvents.push(...t);return}let r=t;if(i&&(this.batchedEvents.length>0&&(r=[...this.batchedEvents,...t]),this.batchedEvents=[],this.shouldBatchEvents=!1),r.length===0)return;const l=r.map(o=>this.enrichChangeWithVirtualProps(o));for(const o of this.changeSubscriptions)o.emitEvents(l)}subscribeChanges(t,i={}){if(this.addSubscriber(),i.where&&i.whereExpression)throw new Error(`Cannot specify both 'where' and 'whereExpression' options. Use one or the other.`);const{where:r,...l}=i;let o=l.whereExpression;if(r){const d=Jv(),p=r(d);o=ne(p)}const u=new AT(this.collection,t,{...l,whereExpression:o,onUnsubscribe:()=>{this.removeSubscriber(),this.changeSubscriptions.delete(u)}});return i.onStatusChange&&u.on(`status:change`,i.onStatusChange),i.includeInitialState?u.requestSnapshot({trackLoadSubsetPromise:!1,orderBy:i.orderBy,limit:i.limit,onLoadSubsetResult:i.onLoadSubsetResult}):i.includeInitialState===!1&&u.markAllStateAsSeen(),this.changeSubscriptions.add(u),u}addSubscriber(){const t=this.activeSubscribersCount;this.activeSubscribersCount++,this.lifecycle.cancelGCTimer(),(this.lifecycle.status===`cleaned-up`||this.lifecycle.status===`idle`)&&this.sync.startSync(),this.events.emitSubscribersChange(this.activeSubscribersCount,t)}removeSubscriber(){const t=this.activeSubscribersCount;if(this.activeSubscribersCount--,this.activeSubscribersCount===0)this.lifecycle.startGCTimer();else if(this.activeSubscribersCount<0)throw new UC;this.events.emitSubscribersChange(this.activeSubscribersCount,t)}cleanup(){this.batchedEvents=[],this.shouldBatchEvents=!1}}const RT=n=>setTimeout(()=>{n({didTimeout:!0,timeRemaining:()=>50})},0),DT=n=>{clearTimeout(n)},MT=typeof window<`u`&&`requestIdleCallback`in window?(n,t)=>window.requestIdleCallback(n,t):(n,t)=>RT(n),Ih=typeof window<`u`&&`cancelIdleCallback`in window?n=>window.cancelIdleCallback(n):DT,Wv=class fs{constructor(){this.tasks=new Map,this.timeoutId=null,this.microtaskScheduled=!1}static getInstance(){return fs.instance||(fs.instance=new fs),fs.instance}schedule(t,i,r){const l=Date.now()+i;this.tasks.set(t,{executeAt:l,callback:r}),this.microtaskScheduled||(this.microtaskScheduled=!0,Promise.resolve().then(()=>{this.microtaskScheduled=!1,this.updateTimeout()}))}cancel(t){this.tasks.delete(t)}updateTimeout(){if(this.timeoutId!==null&&(clearTimeout(this.timeoutId),this.timeoutId=null),this.tasks.size===0)return;let t=1/0;for(const r of this.tasks.values())r.executeAtthis.process(),i)}process(){this.timeoutId=null;const t=Date.now();for(const[i,r]of this.tasks.entries())if(t>=r.executeAt){this.tasks.delete(i);try{r.callback()}catch(l){console.error(`Error in CleanupQueue task:`,l)}}this.tasks.size>0&&this.updateTimeout()}static resetInstance(){fs.instance&&(fs.instance.timeoutId!==null&&clearTimeout(fs.instance.timeoutId),fs.instance=null)}};Wv.instance=null;let Hh=Wv;class kT{constructor(t,i){this.status=`idle`,this.hasBeenReady=!1,this.hasReceivedFirstCommit=!1,this.onFirstReadyCallbacks=[],this.idleCallbackId=null,this.config=t,this.id=i}setDeps(t){this.indexes=t.indexes,this.events=t.events,this.changes=t.changes,this.sync=t.sync,this.state=t.state}validateStatusTransition(t,i){if(t===i)return;if(!{idle:[`loading`,`error`,`cleaned-up`],loading:[`ready`,`error`,`cleaned-up`],ready:[`cleaned-up`,`error`],error:[`cleaned-up`,`idle`],"cleaned-up":[`loading`,`error`]}[t].includes(i))throw new MC(t,i,this.id)}setStatus(t,i=!1){if(t===`ready`&&!i)throw new Cl(`You can't directly call "setStatus('ready'). You must use markReady instead.`);this.validateStatusTransition(this.status,t);const r=this.status;this.status=t,this.events.emitStatusChange(t,r)}validateCollectionUsable(t){switch(this.status){case`error`:throw new DC(t,this.id);case`cleaned-up`:this.sync.startSync();break}}markReady(){if(this.validateStatusTransition(this.status,`ready`),this.status===`loading`){if(this.setStatus(`ready`,!0),!this.hasBeenReady){this.hasBeenReady=!0,this.hasReceivedFirstCommit||(this.hasReceivedFirstCommit=!0);const t=[...this.onFirstReadyCallbacks];this.onFirstReadyCallbacks=[],t.forEach(i=>i())}this.changes.changeSubscriptions.size>0&&this.changes.emitEmptyReadyEvent()}}startGCTimer(){const t=this.config.gcTime??3e5;t<=0||!Number.isFinite(t)||Hh.getInstance().schedule(this,t,()=>{this.changes.activeSubscribersCount===0&&this.scheduleIdleCleanup()})}cancelGCTimer(){Hh.getInstance().cancel(this),this.idleCallbackId!==null&&(Ih(this.idleCallbackId),this.idleCallbackId=null)}scheduleIdleCleanup(){this.idleCallbackId!==null&&Ih(this.idleCallbackId),this.idleCallbackId=MT(t=>{this.changes.activeSubscribersCount===0?this.performCleanup(t)&&(this.idleCallbackId=null):this.idleCallbackId=null},{timeout:1e3})}performCleanup(t){if(!t||t.timeRemaining()>0||t.didTimeout){this.sync.cleanup(),this.state.cleanup(),this.changes.cleanup(),this.indexes.cleanup(),Hh.getInstance().cancel(this),this.hasBeenReady=!1;const r=[...this.onFirstReadyCallbacks];return this.onFirstReadyCallbacks=[],r.forEach(l=>{try{l()}catch(o){console.error(`${this.config.id?`[${this.config.id}] `:``}Error in onFirstReady callback during cleanup:`,o)}}),this.setStatus(`cleaned-up`),this.events.cleanup(),!0}else return this.scheduleIdleCleanup(),!1}onFirstReady(t){if(this.hasBeenReady){t();return}this.onFirstReadyCallbacks.push(t)}cleanup(){this.idleCallbackId!==null&&(Ih(this.idleCallbackId),this.idleCallbackId=null),this.performCleanup()}}const rp=Symbol(`liveQueryInternal`);class UT{constructor(t,i){this.preloadPromise=null,this.syncCleanupFn=null,this.syncLoadSubsetFn=null,this.syncUnloadSubsetFn=null,this.pendingLoadSubsetPromises=new Set,this.config=t,this.id=i,this.syncMode=t.syncMode??`eager`}setDeps(t){this.collection=t.collection,this.state=t.state,this.lifecycle=t.lifecycle,this._events=t.events}startSync(){if(!(this.lifecycle.status!==`idle`&&this.lifecycle.status!==`cleaned-up`)){this.lifecycle.setStatus(`loading`);try{const t=zT(this.config.sync.sync({collection:this.collection,begin:i=>{this.state.pendingSyncedTransactions.push({committed:!1,operations:[],deletedKeys:new Set,rowMetadataWrites:new Map,collectionMetadataWrites:new Map,immediate:i?.immediate})},write:i=>{const r=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(!r)throw new Dh;if(r.committed)throw new Mh;let l;`key`in i?l=i.key:l=this.config.getKey(i.value),this.state.pendingLocalChanges.has(l)&&this.state.pendingLocalOrigins.add(l);let o=i.type;if(i.type===`insert`){const d=this.state.syncedData.has(l),p=r.deletedKeys.has(l),g=r.truncate===!0;if(d&&!p&&!g){const y=this.state.syncedData.get(l);if(y!==void 0&&Bn(y,i.value))o=`update`;else{const w=this.config.utils[rp];throw new BC(l,this.id,{hasCustomGetKey:w?.hasCustomGetKey??!1,hasJoins:w?.hasJoins??!1,hasDistinct:w?.hasDistinct??!1})}}}const u={...i,type:o,key:l};r.operations.push(u),o===`delete`?(r.deletedKeys.add(l),r.rowMetadataWrites.set(l,{type:`delete`})):o===`insert`?u.metadata!==void 0?r.rowMetadataWrites.set(l,{type:`set`,value:u.metadata}):r.rowMetadataWrites.set(l,{type:`delete`}):u.metadata!==void 0&&r.rowMetadataWrites.set(l,{type:`set`,value:u.metadata})},commit:()=>{const i=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(!i)throw new WC;if(i.committed)throw new PC;i.committed=!0,this.state.commitPendingTransactions()},markReady:()=>{this.lifecycle.markReady()},truncate:()=>{const i=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(!i)throw new Dh;if(i.committed)throw new Mh;i.operations=[],i.deletedKeys.clear(),i.rowMetadataWrites.clear(),i.truncate=!0,i.optimisticSnapshot={upserts:new Map(this.state.optimisticUpserts),deletes:new Set(this.state.optimisticDeletes)}},metadata:this.createSyncMetadataApi()}));if(this.syncCleanupFn=t?.cleanup??null,this.syncLoadSubsetFn=t?.loadSubset??null,this.syncUnloadSubsetFn=t?.unloadSubset??null,this.syncMode===`on-demand`&&!this.syncLoadSubsetFn)throw new Ai(`Collection "${this.id}" is configured with syncMode "on-demand" but the sync function did not return a loadSubset handler. Either provide a loadSubset handler or use syncMode "eager".`)}catch(t){throw this.lifecycle.setStatus(`error`),t}}}getActivePendingSyncTransaction(){const t=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(!t)throw new Dh;if(t.committed)throw new Mh;return t}createSyncMetadataApi(){return{row:{get:t=>{const i=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1],r=i?.rowMetadataWrites.get(t);if(r)return r.type===`delete`?void 0:r.value;if(!i?.truncate)return this.state.syncedMetadata.get(t)},set:(t,i)=>{this.getActivePendingSyncTransaction().rowMetadataWrites.set(t,{type:`set`,value:i})},delete:t=>{this.getActivePendingSyncTransaction().rowMetadataWrites.set(t,{type:`delete`})}},collection:{get:t=>{const r=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1]?.collectionMetadataWrites.get(t);return r?r.type===`delete`?void 0:r.value:this.state.syncedCollectionMetadata.get(t)},set:(t,i)=>{this.getActivePendingSyncTransaction().collectionMetadataWrites.set(t,{type:`set`,value:i})},delete:t=>{this.getActivePendingSyncTransaction().collectionMetadataWrites.set(t,{type:`delete`})},list:t=>{const i=new Map(this.state.syncedCollectionMetadata),r=this.state.pendingSyncedTransactions[this.state.pendingSyncedTransactions.length-1];if(r)for(const[l,o]of r.collectionMetadataWrites)o.type===`delete`?i.delete(l):i.set(l,o.value);return Array.from(i.entries()).filter(([l])=>t?l.startsWith(t):!0).map(([l,o])=>({key:l,value:o}))}}}}preload(){return this.preloadPromise?this.preloadPromise:(this.syncMode===`on-demand`&&console.warn(`${this.id?`[${this.id}] `:``}Calling .preload() on a collection with syncMode "on-demand" is a no-op. In on-demand mode, data is only loaded when queries request it. Instead, create a live query and call .preload() on that to load the specific data you need. See https://tanstack.com/blog/tanstack-db-0.5-query-driven-sync for more details.`),this.preloadPromise=new Promise((t,i)=>{if(this.lifecycle.status===`ready`){t();return}if(this.lifecycle.status===`error`){i(new kC);return}if(this.lifecycle.onFirstReady(()=>{t()}),this.lifecycle.status===`idle`||this.lifecycle.status===`cleaned-up`)try{this.startSync()}catch(r){i(r);return}}),this.preloadPromise)}get isLoadingSubset(){return this.pendingLoadSubsetPromises.size>0}trackLoadPromise(t){const i=!this.isLoadingSubset;this.pendingLoadSubsetPromises.add(t),i&&this._events.emit(`loadingSubset:change`,{type:`loadingSubset:change`,collection:this.collection,isLoadingSubset:!0,previousIsLoadingSubset:!1,loadingSubsetTransition:`start`}),t.finally(()=>{const r=this.pendingLoadSubsetPromises.size===1&&this.pendingLoadSubsetPromises.has(t);this.pendingLoadSubsetPromises.delete(t),r&&this._events.emit(`loadingSubset:change`,{type:`loadingSubset:change`,collection:this.collection,isLoadingSubset:!1,previousIsLoadingSubset:!0,loadingSubsetTransition:`end`})})}loadSubset(t){if(this.syncMode===`eager`)return!0;if(this.syncLoadSubsetFn){const i=this.syncLoadSubsetFn(t);if(i instanceof Promise)return this.trackLoadPromise(i),i}return!0}unloadSubset(t){this.syncUnloadSubsetFn&&this.syncUnloadSubsetFn(t)}cleanup(){try{this.syncCleanupFn&&(this.syncCleanupFn(),this.syncCleanupFn=null)}catch(t){queueMicrotask(()=>{if(t instanceof Error){const i=new nS(this.id,t);throw i.cause=t,i.stack=t.stack,i}else throw new nS(this.id,t)})}this.preloadPromise=null}}function zT(n){if(typeof n==`function`)return{cleanup:n};if(typeof n==`object`)return n}const wS=1;function cc(n,t){return n===t?0:nGs(r)??null);if(n instanceof Date)return{__type:`date`,value:n.toISOString()};if(n instanceof Set)return{__type:`set`,values:Array.from(n).map(l=>Gs(l)??null).sort((l,o)=>cc(bi(l),bi(o)))};if(n instanceof Map)return{__type:`map`,entries:Array.from(n.entries()).map(([l,o])=>({key:Gs(l)??null,value:Gs(o)??null})).sort((l,o)=>cc(bi(l.key),bi(o.key)))};if(n instanceof RegExp)return{__type:`regexp`,value:n.toString()};const t={},i=Object.entries(n).sort(([r],[l])=>cc(r,l));for(const[r,l]of i){const o=Gs(l);o!==void 0&&(t[r]=o)}return t}function bi(n){return n===null?`null`:Array.isArray(n)?`[${n.map(bi).join(`,`)}]`:typeof n!=`object`?JSON.stringify(n):`{${Object.keys(n).sort((r,l)=>cc(r,l)).map(r=>`${JSON.stringify(r)}:${bi(n[r])}`).join(`,`)}}`}function jT(n,t,i,r,l){const o=NT(r),u=Gs(t)??null,d=Gs(l),g=Gs({signatureVersion:wS,expression:u,options:d??null})??null,y=bi(g);return{signatureVersion:wS,signature:y,indexId:n,name:i,expression:t,resolver:o,...d===void 0?{}:{options:d}}}function xd(n){if(n===null||typeof n!=`object`)return n;if(Array.isArray(n))return n.map(i=>xd(i));const t={};for(const[i,r]of Object.entries(n))t[i]=xd(r);return t}function BT(n){return JSON.parse(JSON.stringify(n))}class LT{constructor(){this.indexes=new Map,this.indexMetadata=new Map,this.indexCounter=0}setDeps(t){this.state=t.state,this.lifecycle=t.lifecycle,this.defaultIndexType=t.defaultIndexType,this.events=t.events}createIndex(t,i={}){this.lifecycle.validateCollectionUsable(`createIndex`);const r=++this.indexCounter,l=Jv(),o=t(l),u=ne(o),d=i.indexType??this.defaultIndexType;if(!d)throw new Ai(`No index type specified and no defaultIndexType set on collection. Either pass indexType in config, or set defaultIndexType on the collection: + import { BasicIndex } from '@tanstack/db' + createCollection({ defaultIndexType: BasicIndex, ... })`);const p=new d(r,u,i.name,i.options);p.build(this.state.entries()),this.indexes.set(r,p);const g=jT(r,u,i.name,d,i.options);return this.indexMetadata.set(r,g),this.events.emitIndexAdded(g),p}removeIndex(t){this.lifecycle.validateCollectionUsable(`removeIndex`);const i=typeof t==`number`?t:t.id,r=this.indexes.get(i);if(!r||typeof t!=`number`&&r!==t)return!1;this.indexes.delete(i);const l=this.indexMetadata.get(i);return this.indexMetadata.delete(i),l&&this.events.emitIndexRemoved(l),!0}getIndexMetadataSnapshot(){return Array.from(this.indexMetadata.values()).sort((t,i)=>t.indexId-i.indexId).map(t=>({...t,expression:BT(t.expression),resolver:{...t.resolver},...t.options===void 0?{}:{options:xd(t.options)}}))}updateIndexes(t){for(const i of this.indexes.values())for(const r of t)switch(r.type){case`insert`:i.add(r.key,r.value);break;case`update`:r.previousValue?i.update(r.key,r.previousValue,r.value):i.add(r.key,r.value);break;case`delete`:i.remove(r.key,r.value);break}}cleanup(){this.indexes.clear(),this.indexMetadata.clear()}}var IT={};const HT=new Set([`find`,`findLast`,`findIndex`,`findLastIndex`,`filter`,`map`,`flatMap`,`forEach`,`some`,`every`,`reduce`,`reduceRight`]),qT=new Set([`pop`,`push`,`shift`,`unshift`,`splice`,`sort`,`reverse`,`fill`,`copyWithin`]),KT=new Set([`set`,`delete`,`clear`,`add`]),VT=new Set([`entries`,`keys`,`values`,`forEach`]);function ap(n){return n!==null&&typeof n==`object`&&!(n instanceof Date)&&!(n instanceof RegExp)&&!Xs(n)}function $T(n,t,i,r){if(HT.has(n))return function(...l){const o=l[0];if(typeof o!=`function`)return t.apply(i.copy_,l);const u=(g,y)=>{if(ap(g)){const m={tracker:i,prop:String(y)},{proxy:v}=r(g,m);return v}return g},d=function(g,y,m){const v=u(g,y);return o.call(this,v,y,m)};if(n===`reduce`||n===`reduceRight`){const g=function(y,m,v,w){const b=u(m,v);return o.call(this,y,b,v,w)};return t.apply(i.copy_,[g,...l.slice(1)])}const p=t.apply(i.copy_,[d,...l.slice(1)]);if((n===`find`||n===`findLast`)&&p&&typeof p==`object`){const g=i.copy_.indexOf(p);if(g!==-1)return u(p,g)}return n===`filter`&&Array.isArray(p)?p.map(g=>{const y=i.copy_.indexOf(g);return y!==-1?u(g,y):g}):p}}function GT(n,t){return function(){const i=n.copy_;let r=0;return{next(){if(r>=i.length)return{done:!0,value:void 0};const l=i[r];let o=l;if(ap(l)){const u={tracker:n,prop:String(r)},{proxy:d}=t(l,u);o=d}return r++,{done:!1,value:o}},[Symbol.iterator](){return this}}}}function ES(n,t,i){return function(...r){const l=n.apply(t.copy_,r);return i(t),l}}function YT(n,t,i,r,l,o,u){if(VT.has(n)||t===Symbol.iterator)return function(...p){const g=i.apply(l.copy_,p);if(n===`forEach`){const m=p[0];if(typeof m==`function`){const v=function(w,b,E){const _=m.call(this,w,b,E);return u(l),_};return i.apply(r,[v,...p.slice(1)])}}if(n===`entries`||n===`values`||n===Symbol.iterator.toString()||t===Symbol.iterator){const m=g,v=new Map;if(n===`values`&&r instanceof Map)for(const[b,E]of l.copy_.entries())v.set(E,b);const w=new Map;if(r instanceof Set)for(const b of l.copy_.values())w.set(b,b);return{next(){const b=m.next();if(!b.done&&b.value&&typeof b.value==`object`){if(n===`entries`&&Array.isArray(b.value)&&b.value.length===2){if(b.value[1]&&typeof b.value[1]==`object`){const E=b.value[0],_={tracker:l,prop:E,updateMap:O=>{l.copy_ instanceof Map&&l.copy_.set(E,O)}},{proxy:j}=o(b.value[1],_);b.value[1]=j}}else if(n===`values`||n===Symbol.iterator.toString()||t===Symbol.iterator)if(n===`values`&&r instanceof Map){const E=v.get(b.value);if(E!==void 0){const _={tracker:l,prop:E,updateMap:O=>{l.copy_ instanceof Map&&l.copy_.set(E,O)}},{proxy:j}=o(b.value,_);b.value=j}}else if(r instanceof Set){const E=b.value,_={tracker:l,prop:E,updateSet:O=>{l.copy_ instanceof Set&&(l.copy_.delete(E),l.copy_.add(O),w.set(E,O))}},{proxy:j}=o(b.value,_);b.value=j}else{const E=Symbol(`iterator-value`),{proxy:_}=o(b.value,{tracker:l,prop:E});b.value=_}}return b},[Symbol.iterator](){return this}}}return g}}function Tt(...n){const t=typeof window<`u`&&typeof localStorage<`u`;t&&localStorage.getItem(`DEBUG`)===`true`?console.log(`[proxy]`,...n):!t&&typeof process<`u`&&IT.DEBUG===`true`&&console.log(`[proxy]`,...n)}function ds(n,t=new WeakMap){if(n==null||typeof n!=`object`)return n;if(t.has(n))return t.get(n);if(n instanceof Date)return new Date(n.getTime());if(n instanceof RegExp)return new RegExp(n.source,n.flags);if(Array.isArray(n)){const l=[];return t.set(n,l),n.forEach((o,u)=>{l[u]=ds(o,t)}),l}if(ArrayBuffer.isView(n)&&!(n instanceof DataView)){const l=Object.getPrototypeOf(n).constructor,o=new l(n.length);t.set(n,o);for(let u=0;u{l.set(u,ds(o,t))}),l}if(n instanceof Set){const l=new Set;return t.set(n,l),n.forEach(o=>{l.add(ds(o,t))}),l}if(Xs(n))return n;const i={};t.set(n,i);for(const l in n)Object.prototype.hasOwnProperty.call(n,l)&&(i[l]=ds(n[l],t));const r=Object.getOwnPropertySymbols(n);for(const l of r)i[l]=ds(n[l],t);return i}let CS=0;function FT(){return CS+=1,CS}function lp(n,t){const i=new Map;function r(m,v){if(Tt(`Object ID:`,m.constructor.name),i.has(m))return i.get(m);{const w=lp(m,v);return i.set(m,w),w}}const l=new Map,o={copy_:ds(n),originalObject:ds(n),proxyCount:FT(),modified:!1,assigned_:{},parent:t,target:n};Tt(`createChangeProxy called for target`,n,o.proxyCount);function u(m){m.modified||(m.modified=!0),m.parent&&(Tt(`propagating change to parent`),`updateMap`in m.parent?m.parent.updateMap(m.copy_):`updateSet`in m.parent?m.parent.updateSet(m.copy_):(m.parent.tracker.copy_[m.parent.prop]=m.copy_,m.parent.tracker.assigned_[m.parent.prop]=!0),u(m.parent.tracker))}function d(m){if(Tt(`checkIfReverted called with assigned keys:`,Object.keys(m.assigned_)),Object.keys(m.assigned_).length===0&&Object.getOwnPropertySymbols(m.assigned_).length===0)return Tt(`No assigned properties, returning true`),!0;for(const w in m.assigned_)if(m.assigned_[w]===!0){const b=m.copy_[w],E=m.originalObject[w];if(Tt(`Checking property ${String(w)}, current:`,b,`original:`,E),!Bn(b,E))return Tt(`Property ${String(w)} is different, returning false`),!1}else if(m.assigned_[w]===!1)return Tt(`Property ${String(w)} was deleted, returning false`),!1;const v=Object.getOwnPropertySymbols(m.assigned_);for(const w of v)if(m.assigned_[w]===!0){const b=m.copy_[w],E=m.originalObject[w];if(!Bn(b,E))return Tt(`Symbol property is different, returning false`),!1}else if(m.assigned_[w]===!1)return Tt(`Symbol property was deleted, returning false`),!1;return Tt(`All properties match original values, returning true`),!0}function p(m,v){Tt(`checkParentStatus called for child prop:`,v);const w=d(m);Tt(`Parent checkIfReverted returned:`,w),w&&(Tt(`Parent is fully reverted, clearing tracking`),m.modified=!1,m.assigned_={},m.parent&&(Tt(`Continuing up the parent chain`),p(m.parent.tracker,m.parent.prop)))}function g(m){if(Tt(`createObjectProxy`,m),l.has(m))return Tt(`proxyCache found match`),l.get(m);const v=new Proxy(m,{get(w,b){Tt(`get`,w,b);const E=o.copy_[b]??o.originalObject[b],_=o.originalObject[b];if(Tt(`value (at top of proxy get)`,E),Object.getOwnPropertyDescriptor(w,b)?.get)return E;if(typeof E==`function`){if(Array.isArray(w)){const O=b.toString();if(qT.has(O))return ES(E,o,u);const A=$T(O,E,o,r);if(A)return A;if(b===Symbol.iterator)return GT(o,r)}if(w instanceof Map||w instanceof Set){const O=b.toString();if(KT.has(O))return ES(E,o,u);const A=YT(O,b,E,w,o,r,u);if(A)return A}return E.bind(w)}if(ap(E)){const O={tracker:o,prop:String(b)},{proxy:A}=r(_,O);return l.set(E,A),A}return E},set(w,b,E){const _=o.copy_[b];if(Tt(`set called for property ${String(b)}, current:`,_,`new:`,E),Bn(_,E))Tt(`Value unchanged, not tracking`);else{const j=o.originalObject[b],O=Bn(E,j);if(Tt(`value:`,E,`original:`,j,`isRevertToOriginal:`,O),O){Tt(`Reverting property ${String(b)} to original value`),delete o.assigned_[b.toString()],Tt(`Updating copy with original value for ${String(b)}`),o.copy_[b]=ds(j),Tt(`Checking if all properties reverted`);const A=d(o);Tt(`All reverted:`,A),A?(Tt(`All properties reverted, clearing tracking`),o.modified=!1,o.assigned_={},t&&(Tt(`Updating parent for property:`,t.prop),p(t.tracker,t.prop))):(Tt(`Some properties still changed, keeping modified flag`),o.modified=!0)}else Tt(`Setting new value for property ${String(b)}`),o.copy_[b]=E,o.assigned_[b.toString()]=!0,Tt(`Marking object and ancestors as modified`,o),u(o)}return!0},defineProperty(w,b,E){const _=Reflect.defineProperty(w,b,E);return _&&`value`in E&&(o.copy_[b]=ds(E.value),o.assigned_[b.toString()]=!0,u(o)),_},getOwnPropertyDescriptor(w,b){return Reflect.getOwnPropertyDescriptor(w,b)},preventExtensions(w){return Reflect.preventExtensions(w)},isExtensible(w){return Reflect.isExtensible(w)},deleteProperty(w,b){Tt(`deleteProperty`,w,b);const E=typeof b==`symbol`?b.toString():b;if(E in w){const _=E in o.originalObject,j=Reflect.deleteProperty(w,b);return j&&(_?(o.assigned_[E]=!1,u(o)):(delete o.assigned_[E],Object.keys(o.assigned_).length===0&&Object.getOwnPropertySymbols(o.assigned_).length===0?o.modified=!1:o.modified=!0)),j}return!0}});return l.set(m,v),v}return{proxy:g(o.copy_),getChanges:()=>{if(Tt(`getChanges called, modified:`,o.modified),Tt(o),!o.modified)return Tt(`Object not modified, returning empty object`),{};if(typeof o.copy_!=`object`||Array.isArray(o.copy_)||Object.keys(o.assigned_).length===0)return o.copy_;const m={};for(const v in o.copy_)o.assigned_[v]===!0&&v in o.copy_&&(m[v]=o.copy_[v]);return Tt(`Returning copy:`,m),m}}}function QT(n){const t=n.map(i=>lp(i));return{proxies:t.map(i=>i.proxy),getChanges:()=>t.map(i=>i.getChanges())}}function XT(n,t){const{proxy:i,getChanges:r}=lp(n);return t(i),r()}function JT(n,t){const{proxies:i,getChanges:r}=QT(n);return t(i),r()}function ZT(){let n,t,i=!0;return{promise:new Promise((l,o)=>{n=u=>{i=!1,l(u)},t=u=>{i=!1,o(u)}}),resolve:n,reject:t,isPending:()=>i}}function WT(n){return typeof n==`object`&&n!==null&&typeof n.hasPendingGraphRun==`function`}class PT{constructor(){this.contexts=new Map,this.clearListeners=new Set}getOrCreateContext(t){let i=this.contexts.get(t);return i||(i={queue:[],jobs:new Map,dependencies:new Map,completed:new Set},this.contexts.set(t,i)),i}schedule({contextId:t,jobId:i,dependencies:r,run:l}){if(typeof t>`u`){l();return}const o=this.getOrCreateContext(t);if(o.jobs.has(i)||o.queue.push(i),o.jobs.set(i,l),r){const u=new Set(r);u.delete(i),o.dependencies.set(i,u)}else o.dependencies.has(i)||o.dependencies.set(i,new Set);o.completed.delete(i)}flush(t){const i=this.contexts.get(t);if(!i)return;const{queue:r,jobs:l,dependencies:o,completed:u}=i;for(;r.length>0;){let d=!1;const p=r.length;for(let g=0;gi(t))}onClear(t){return this.clearListeners.add(t),()=>this.clearListeners.delete(t)}hasPendingJobs(t){const i=this.contexts.get(t);return!!i&&i.jobs.size>0}clearJob(t,i){const r=this.contexts.get(t);r&&(r.jobs.delete(i),r.dependencies.delete(i),r.completed.delete(i),r.queue=r.queue.filter(l=>l!==i),r.jobs.size===0&&this.contexts.delete(t))}}const xc=new PT,_c=[];let fl=[],tA=0;function eA(n,t){switch(`${n.type}-${t.type}`){case`insert-update`:return{...n,type:`insert`,original:{},modified:t.modified,changes:{...n.changes,...t.changes},key:n.key,globalKey:n.globalKey,metadata:t.metadata??n.metadata,syncMetadata:{...n.syncMetadata,...t.syncMetadata},mutationId:t.mutationId,updatedAt:t.updatedAt};case`insert-delete`:return null;case`update-delete`:return t;case`update-update`:return{...t,original:n.original,changes:{...n.changes,...t.changes},metadata:t.metadata??n.metadata,syncMetadata:{...n.syncMetadata,...t.syncMetadata}};case`delete-delete`:case`insert-insert`:return t;default:{const i=`${n.type}-${t.type}`;throw new Error(`Unhandled mutation combination: ${i}`)}}}function Za(n){const t=new rA(n);return _c.push(t),t}function uc(){if(fl.length>0)return fl.slice(-1)[0]}function nA(n){xc.clear(n.id),fl.push(n)}function sA(n){try{xc.flush(n.id)}finally{fl=fl.filter(t=>t.id!==n.id)}}function iA(n){const t=_c.findIndex(i=>i.id===n.id);t!==-1&&_c.splice(t,1)}let rA=class{constructor(t){if(typeof t.mutationFn>`u`)throw new FC;this.id=t.id??crypto.randomUUID(),this.mutationFn=t.mutationFn,this.state=`pending`,this.mutations=[],this.isPersisted=ZT(),this.autoCommit=t.autoCommit??!0,this.createdAt=new Date,this.sequenceNumber=tA++,this.metadata=t.metadata??{}}setState(t){this.state=t,(t===`completed`||t===`failed`)&&iA(this)}mutate(t){if(this.state!==`pending`)throw new XC;nA(this);try{t()}finally{sA(this)}return this.autoCommit&&this.commit().catch(()=>{}),this}applyMutations(t){for(const i of t){const r=this.mutations.findIndex(l=>l.globalKey===i.globalKey);if(r>=0){const l=this.mutations[r],o=eA(l,i);o===null?this.mutations.splice(r,1):this.mutations[r]=o}else this.mutations.push(i)}}rollback(t){const i=t?.isSecondaryRollback??!1;if(this.state===`completed`)throw new JC;if(this.setState(`failed`),!i){const r=new Set;this.mutations.forEach(l=>r.add(l.globalKey));for(const l of _c)l.state===`pending`&&l.mutations.some(o=>r.has(o.globalKey))&&l.rollback({isSecondaryRollback:!0})}return this.isPersisted.reject(this.error?.error),this.touchCollection(),this}touchCollection(){const t=new Set;for(const i of this.mutations)t.has(i.collection.id)||(i.collection._state.onTransactionStateChange(),i.collection._state.pendingSyncedTransactions.length>0&&i.collection._state.commitPendingTransactions(),t.add(i.collection.id))}async commit(){if(this.state!==`pending`)throw new ZC;if(this.setState(`persisting`),this.mutations.length===0)return this.setState(`completed`),this.isPersisted.resolve(this),this;try{await this.mutationFn({transaction:this}),this.setState(`completed`),this.touchCollection(),this.isPersisted.resolve(this)}catch(t){const i=t instanceof Error?t:new Error(String(t));throw this.error={message:i.message,error:i},this.rollback(),i}return this}compareCreatedAt(t){const i=this.createdAt.getTime()-t.createdAt.getTime();return i!==0?i:this.sequenceNumber-t.sequenceNumber}};class aA{constructor(t,i){this.insert=(r,l)=>{this.lifecycle.validateCollectionUsable(`insert`);const o=this.state,u=uc();if(!u&&!this.config.onInsert)throw new $C;const d=Array.isArray(r)?r:[r],p=[],g=new Set;if(d.forEach(y=>{const m=this.validateData(y,`insert`),v=this.config.getKey(m);if(this.state.has(v)||g.has(v))throw new jC(v);g.add(v);const w=this.generateGlobalKey(v,y),b={mutationId:crypto.randomUUID(),original:{},modified:m,changes:Object.fromEntries(Object.keys(y).map(E=>[E,m[E]])),globalKey:w,key:v,metadata:l?.metadata,syncMetadata:this.config.sync.getSyncMetadata?.()||{},optimistic:l?.optimistic??!0,type:`insert`,createdAt:new Date,updatedAt:new Date,collection:this.collection};p.push(b)}),u)return u.applyMutations(p),o.transactions.set(u.id,u),o.scheduleTransactionCleanup(u),o.recomputeOptimisticState(!0),u;{const y=Za({metadata:{[lc]:!0},mutationFn:async m=>await this.config.onInsert({transaction:m.transaction,collection:this.collection})});return y.applyMutations(p),this.markPendingLocalOrigins(p),y.commit().catch(()=>{}),o.transactions.set(y.id,y),o.scheduleTransactionCleanup(y),o.recomputeOptimisticState(!0),y}},this.delete=(r,l)=>{const o=this.state;this.lifecycle.validateCollectionUsable(`delete`);const u=uc();if(!u&&!this.config.onDelete)throw new YC;if(Array.isArray(r)&&r.length===0)throw new KC;const d=Array.isArray(r)?r:[r],p=[];for(const y of d){if(!this.state.has(y))throw new VC(y);const m=this.generateGlobalKey(y,this.state.get(y)),v={mutationId:crypto.randomUUID(),original:this.state.get(y),modified:this.state.get(y),changes:this.state.get(y),globalKey:m,key:y,metadata:l?.metadata,syncMetadata:o.syncedMetadata.get(y)||{},optimistic:l?.optimistic??!0,type:`delete`,createdAt:new Date,updatedAt:new Date,collection:this.collection};p.push(v)}if(u)return u.applyMutations(p),o.transactions.set(u.id,u),o.scheduleTransactionCleanup(u),o.recomputeOptimisticState(!0),u;const g=Za({autoCommit:!0,metadata:{[lc]:!0},mutationFn:async y=>this.config.onDelete({transaction:y.transaction,collection:this.collection})});return g.applyMutations(p),this.markPendingLocalOrigins(p),g.commit().catch(()=>{}),o.transactions.set(g.id,g),o.scheduleTransactionCleanup(g),o.recomputeOptimisticState(!0),g},this.id=i,this.config=t}setDeps(t){this.lifecycle=t.lifecycle,this.state=t.state,this.collection=t.collection}ensureStandardSchema(t){if(t&&`~standard`in t)return t;throw new RC}validateData(t,i,r){if(!this.config.schema)return t;const l=this.ensureStandardSchema(this.config.schema);if(i===`update`&&r){const u=this.state.get(r);if(u&&t&&typeof t==`object`&&typeof u==`object`){const d=Object.assign({},u,t),p=l[`~standard`].validate(d);if(p instanceof Promise)throw new P0;if(`issues`in p&&p.issues){const v=p.issues.map(w=>({message:w.message,path:w.path?.map(b=>String(b))}));throw new W0(i,v)}const g=p.value,y=Object.keys(t);return Object.fromEntries(y.map(v=>[v,g[v]]))}}const o=l[`~standard`].validate(t);if(o instanceof Promise)throw new P0;if(`issues`in o&&o.issues){const u=o.issues.map(d=>({message:d.message,path:d.path?.map(p=>String(p))}));throw new W0(i,u)}return o.value}generateGlobalKey(t,i){if(typeof t!=`string`&&typeof t!=`number`)throw typeof t>`u`?new zC(i):new NC(t,i);return`KEY::${this.id}/${t}`}markPendingLocalOrigins(t){for(const i of t)this.state.pendingLocalOrigins.add(i.key)}update(t,i,r){if(typeof t>`u`)throw new LC;const l=this.state;this.lifecycle.validateCollectionUsable(`update`);const o=uc();if(!o&&!this.config.onUpdate)throw new GC;const u=Array.isArray(t),d=u?t:[t];if(u&&d.length===0)throw new IC;const p=typeof i==`function`?i:r,g=typeof i==`function`?{}:i,y=d.map(b=>{const E=this.state.get(b);if(!E)throw new HC(b);return E});let m;u?m=JT(y,p):m=[XT(y[0],p)];const v=d.map((b,E)=>{const _=m[E];if(!_||Object.keys(_).length===0)return null;const j=y[E],O=this.validateData(_,`update`,b),A=Object.assign({},j,O),M=this.config.getKey(j),G=this.config.getKey(A);if(M!==G)throw new qC(M,G);const q=this.generateGlobalKey(G,A);return{mutationId:crypto.randomUUID(),original:j,modified:A,changes:Object.fromEntries(Object.keys(_).map(K=>[K,A[K]])),globalKey:q,key:b,metadata:g.metadata,syncMetadata:l.syncedMetadata.get(b)||{},optimistic:g.optimistic??!0,type:`update`,createdAt:new Date,updatedAt:new Date,collection:this.collection}}).filter(Boolean);if(v.length===0){const b=Za({mutationFn:async()=>{}});return b.commit().catch(()=>{}),l.scheduleTransactionCleanup(b),b}if(o)return o.applyMutations(v),l.transactions.set(o.id,o),l.scheduleTransactionCleanup(o),l.recomputeOptimisticState(!0),o;const w=Za({metadata:{[lc]:!0},mutationFn:async b=>this.config.onUpdate({transaction:b.transaction,collection:this.collection})});return w.applyMutations(v),this.markPendingLocalOrigins(v),w.commit().catch(()=>{}),l.transactions.set(w.id,w),l.scheduleTransactionCleanup(w),l.recomputeOptimisticState(!0),w}}class lA extends Zv{constructor(){super()}setDeps(t){this.collection=t.collection}emit(t,i){this.emitInner(t,i)}emitStatusChange(t,i){this.emit(`status:change`,{type:`status:change`,collection:this.collection,previousStatus:i,status:t});const r=`status:${t}`;this.emit(r,{type:r,collection:this.collection,previousStatus:i,status:t})}emitSubscribersChange(t,i){this.emit(`subscribers:change`,{type:`subscribers:change`,collection:this.collection,previousSubscriberCount:i,subscriberCount:t})}emitIndexAdded(t){this.emit(`index:added`,{type:`index:added`,collection:this.collection,index:t})}emitIndexRemoved(t){this.emit(`index:removed`,{type:`index:removed`,collection:this.collection,index:t})}cleanup(){this.clearListeners()}}function op(n){const t=new cp(n);return n.utils?t.utils=n.utils:t.utils={},t}class cp{constructor(t){if(this.utils={},this.deferDataRefresh=null,this.insert=(i,r)=>this._mutations.insert(i,r),this.delete=(i,r)=>this._mutations.delete(i,r),!t)throw new AC;if(!t.sync)throw new OC;if(t.id?this.id=t.id:this.id=crypto.randomUUID(),this.config={...t,autoIndex:t.autoIndex??`off`},this.config.autoIndex===`eager`&&!t.defaultIndexType)throw new Ai(`autoIndex: 'eager' requires defaultIndexType to be set. Import an index type and set it: + import { BasicIndex } from '@tanstack/db' + createCollection({ defaultIndexType: BasicIndex, autoIndex: 'eager', ... })`);this._changes=new OT,this._events=new lA,this._indexes=new LT,this._lifecycle=new kT(t,this.id),this._mutations=new aA(t,this.id),this._state=new bT(t),this._sync=new UT(t,this.id),this.comparisonOpts=oA(t),this._changes.setDeps({collection:this,lifecycle:this._lifecycle,sync:this._sync,events:this._events,state:this._state}),this._events.setDeps({collection:this}),this._indexes.setDeps({state:this._state,lifecycle:this._lifecycle,defaultIndexType:t.defaultIndexType,events:this._events}),this._lifecycle.setDeps({changes:this._changes,events:this._events,indexes:this._indexes,state:this._state,sync:this._sync}),this._mutations.setDeps({collection:this,lifecycle:this._lifecycle,state:this._state}),this._state.setDeps({collection:this,lifecycle:this._lifecycle,changes:this._changes,indexes:this._indexes,events:this._events}),this._sync.setDeps({collection:this,state:this._state,lifecycle:this._lifecycle,events:this._events}),t.startSync===!0&&this._sync.startSync()}get status(){return this._lifecycle.status}get subscriberCount(){return this._changes.activeSubscribersCount}onFirstReady(t){return this._lifecycle.onFirstReady(t)}isReady(){return this._lifecycle.status===`ready`}get isLoadingSubset(){return this._sync.isLoadingSubset}startSyncImmediate(){this._sync.startSync()}preload(){return this._sync.preload()}get(t){return this._state.getWithVirtualProps(t)}has(t){return this._state.has(t)}get size(){return this._state.size}*keys(){yield*this._state.keys()}*values(){for(const t of this._state.keys()){const i=this.get(t);i!==void 0&&(yield i)}}*entries(){for(const t of this._state.keys()){const i=this.get(t);i!==void 0&&(yield[t,i])}}*[Symbol.iterator](){yield*this.entries()}forEach(t){let i=0;for(const[r,l]of this.entries())t(l,r,i++)}map(t){const i=[];let r=0;for(const[l,o]of this.entries())i.push(t(o,l,r++));return i}getKeyFromItem(t){return this.config.getKey(t)}createIndex(t,i={}){return this._indexes.createIndex(t,i)}removeIndex(t){return this._indexes.removeIndex(t)}getIndexMetadata(){return this._indexes.getIndexMetadataSnapshot()}get indexes(){return this._indexes.indexes}validateData(t,i,r){return this._mutations.validateData(t,i,r)}get compareOptions(){return{...this.comparisonOpts}}update(t,i,r){return this._mutations.update(t,i,r)}get state(){const t=new Map;for(const[i,r]of this.entries())t.set(i,r);return t}stateWhenReady(){return this.size>0||this.isReady()?Promise.resolve(this.state):this.preload().then(()=>this.state)}get toArray(){return Array.from(this.values())}toArrayWhenReady(){return this.size>0||this.isReady()?Promise.resolve(this.toArray):this.preload().then(()=>this.toArray)}currentStateAsChanges(t={}){return mT(this,t)}subscribeChanges(t,i={}){return this._changes.subscribeChanges(t,i)}on(t,i){return this._events.on(t,i)}once(t,i){return this._events.once(t,i)}off(t,i){this._events.off(t,i)}waitFor(t,i){return this._events.waitFor(t,i)}async cleanup(){return this._lifecycle.cleanup(),Promise.resolve()}}function oA(n){if(n.defaultStringCollation){const t=n.defaultStringCollation;return{stringSort:t.stringSort??`locale`,locale:t.stringSort===`locale`?t.locale:void 0,localeOptions:t.stringSort===`locale`?t.localeOptions:void 0}}else return{stringSort:`locale`}}function cA(n){return!!n&&(typeof n==`object`||typeof n==`function`)&&typeof n.then==`function`}function uA(n){const{mutationFn:t,onMutate:i,...r}=n;return l=>{const o=Za({...r,mutationFn:async u=>await t(l,u)});return o.mutate(()=>{const u=i(l);if(cA(u))throw new QC}),o}}function fA(n){const t=hA(n);let i=n,r,l=0;const o=10;for(;leb(u)),l=nb(r),o=Pv(n);for(const[u,d]of l.singleSource)dA(n,u)&&!o.has(u)&&t.set(u,d);return t}function dA(n,t){if(n.from.alias===t)return n.from.type===`collectionRef`;if(n.join){for(const i of n.join)if(i.from.alias===t)return i.from.type===`collectionRef`}return!1}function Pv(n){const t=new Set;if(n.join){const i=n.from.alias;for(const r of n.join){const l=r.from.alias;(r.type===`left`||r.type===`full`)&&t.add(l),(r.type===`right`||r.type===`full`)&&t.add(i)}}return t}function _d(n){const t={...n,from:n.from.type===`queryRef`?new Sn(_d(n.from.query),n.from.alias):n.from,join:n.join?.map(i=>({...i,from:i.from.type===`queryRef`?new Sn(_d(i.from.query),i.from.alias):i.from}))};return pA(t)}function pA(n){if(!n.where||n.where.length===0)return n;if(!n.join||n.join.length===0){if(n.where.length>1){const d=Ad(n.where),p=Tc(d);return{...n,where:[p]}}return n}const t=n.where.filter(d=>!Z0(d)),r=Ad(t).map(d=>eb(d)),l=nb(r),o=yA(n,l),u=n.where.filter(d=>Z0(d));return u.length>0&&(o.where=[...o.where||[],...u]),o}function tb(n){return{...n,from:Td(n.from),join:n.join?.map(t=>({...t,from:Td(t.from)}))}}function Td(n){if(n.type===`collectionRef`)return n;const t=tb(n.query);if(gA(t)){const i=Td(t.from);return i.type===`collectionRef`?new jr(i.collection,n.alias):new Sn(i.query,n.alias)}return new Sn(t,n.alias)}function gA(n){return(!n.where||n.where.length===0)&&!n.select&&(!n.groupBy||n.groupBy.length===0)&&(!n.having||n.having.length===0)&&(!n.orderBy||n.orderBy.length===0)&&(!n.join||n.join.length===0)&&n.limit===void 0&&n.offset===void 0&&!n.fnSelect&&(!n.fnWhere||n.fnWhere.length===0)&&(!n.fnHaving||n.fnHaving.length===0)}function Ad(n){const t=[];for(const i of n){const r=Wd(i);t.push(...up(r))}return t}function up(n){if(n.type===`func`&&n.name===`and`){const t=[];for(const i of n.args)t.push(...up(i));return t}else return[n]}function eb(n){const t=new Set;let i=!1;function r(l){switch(l.type){case`ref`:if(l.path&&l.path.length>0){const o=l.path[0];o&&(t.add(o),l.path.length===1&&(i=!0))}break;case`func`:l.args&&l.args.forEach(r);break;case`val`:break;case`agg`:l.args&&l.args.forEach(r);break}}return r(n),{expression:n,touchedSources:t,hasNamespaceOnlyRef:i}}function nb(n){const t=new Map,i=[];for(const o of n)if(o.touchedSources.size===1&&!o.hasNamespaceOnlyRef){const u=Array.from(o.touchedSources)[0];t.has(u)||t.set(u,[]),t.get(u).push(o.expression)}else(o.touchedSources.size>1||o.hasNamespaceOnlyRef)&&i.push(o.expression);const r=new Map;for(const[o,u]of t)r.set(o,Tc(u));const l=i.length>0?Tc(i):void 0;return{singleSource:r,multiSource:l}}function yA(n,t){const i=new Set,r=Pv(n),l=new Map;for(const[m,v]of t.singleSource)r.has(m)||l.set(m,v);const o=xS(n.from,l,i),u=n.join?n.join.map(m=>({...m,from:xS(m.from,l,i)})):void 0,d=[];t.multiSource&&d.push(t.multiSource);const p=r.size>0;for(const[m,v]of t.singleSource)i.has(m)?p&&d.push(_C(v)):d.push(v);const g=d.length>1?[Tc(d.flatMap(m=>up(Wd(m))))]:d;return{select:n.select,groupBy:n.groupBy?[...n.groupBy]:void 0,having:n.having?[...n.having]:void 0,orderBy:n.orderBy?[...n.orderBy]:void 0,limit:n.limit,offset:n.offset,distinct:n.distinct,fnSelect:n.fnSelect,fnWhere:n.fnWhere?[...n.fnWhere]:void 0,fnHaving:n.fnHaving?[...n.fnHaving]:void 0,from:o,join:u,where:g.length>0?g:[]}}function Tr(n){return{from:n.from.type===`collectionRef`?new jr(n.from.collection,n.from.alias):new Sn(Tr(n.from.query),n.from.alias),select:n.select,join:n.join?n.join.map(t=>({type:t.type,left:t.left,right:t.right,from:t.from.type===`collectionRef`?new jr(t.from.collection,t.from.alias):new Sn(Tr(t.from.query),t.from.alias)})):void 0,where:n.where?[...n.where]:void 0,groupBy:n.groupBy?[...n.groupBy]:void 0,having:n.having?[...n.having]:void 0,orderBy:n.orderBy?[...n.orderBy]:void 0,limit:n.limit,offset:n.offset,fnSelect:n.fnSelect,fnWhere:n.fnWhere?[...n.fnWhere]:void 0,fnHaving:n.fnHaving?[...n.fnHaving]:void 0}}function xS(n,t,i){const r=t.get(n.alias);if(!r)return n.type===`collectionRef`?new jr(n.collection,n.alias):new Sn(Tr(n.query),n.alias);if(n.type===`collectionRef`){const u={from:new jr(n.collection,n.alias),where:[r]};return i.add(n.alias),new Sn(u,n.alias)}if(!EA(n.query,r,n.alias))return new Sn(Tr(n.query),n.alias);if(xA(n.query,r,n.alias))return new Sn(Tr(n.query),n.alias);const l=n.query.where||[],o={...Tr(n.query),where:[...l,r]};return i.add(n.alias),new Sn(o,n.alias)}function mA(n,t,i){return n.select?sb(n.select)||CA(n.select,t,i):!1}function SA(n){return n.groupBy&&n.groupBy.length>0}function vA(n){return n.having&&n.having.length>0}function bA(n){return n.orderBy&&n.orderBy.length>0&&(n.limit!==void 0||n.offset!==void 0)}function wA(n){return n.fnSelect||n.fnWhere&&n.fnWhere.length>0||n.fnHaving&&n.fnHaving.length>0}function EA(n,t,i){return!(mA(n,t,i)||SA(n)||vA(n)||bA(n)||wA(n))}function sb(n){for(const t of Object.values(n))if(typeof t==`object`){const i=t;if(i.type===`agg`||!(`type`in i)&&sb(i))return!0}return!1}function fp(n){const t=[];if(n==null||typeof n!=`object`)return t;switch(n.type){case`ref`:t.push(n);break;case`func`:case`agg`:for(const i of n.args??[])t.push(...fp(i));break}return t}function CA(n,t,i){const r=new Set;for(const[o,u]of Object.entries(n))o.startsWith(`__SPREAD_SENTINEL__`)||u instanceof Oe||r.add(o);const l=fp(t);for(const o of l){const u=o.path;if(!Array.isArray(u)||u.length<2)continue;const d=u[0],p=u[1];if(d===i&&r.has(p))return!0}return!1}function xA(n,t,i){const r=fp(t);if(r.every(o=>o.path[0]!==i))return!1;if(n.fnSelect)return!0;const l=n.select;if(!l)return!1;for(const o of r){const u=o.path;if(u.length<2||u[0]!==i)continue;const d=l[u[1]];if(!d)continue;if(!(d instanceof Oe)||d.path.length<2)return!0;const[p,g]=d.path;if(p!==i&&p!==n.from.alias||g!==u[1])return!0}return!1}function Tc(n){if(n.length===0)throw new Ax;return n.length===1?n[0]:new Ve(`and`,n)}function _A(n,t,i,r,l,o,u,d,p,g,y,m,v,w,b,E,_,j,O){let A=n;for(const M of t)A=TA(A,M,i,r,l,o,u,d,p,g,y,m,v,w,b,E,_,j,O);return A}function TA(n,t,i,r,l,o,u,d,p,g,y,m,v,w,b,E,_,j,O){const A=t.from.type===`collectionRef`,{alias:M,input:G,collectionId:q}=OA(t.from,o,p,g,y,m,v,w,u,d,E,_,j,O);i[M]=G,A&&(_[M]=q);const K=p[r],W=p[q];if(!K)throw new eS(r);if(!W)throw new eS(q);const{activeSource:et,lazySource:X}=DA(t.type,K,W),at=Object.keys(i),{mainExpr:nt,joinedExpr:bt}=AA(t.left,t.right,at,M),Lt=ue(nt),dt=ue(bt);let k=n.pipe(le(([Z,it])=>[xr(Lt(it)),[Z,it]])),I=G.pipe(le(([Z,it])=>{const ft={[M]:it};return[xr(dt(ft)),[Z,ft]]}));if(![`inner`,`left`,`right`,`full`].includes(t.type))throw new gx(t.type);if(et){const Z=et===`main`?t.from:b.from,it=Z.type===`queryRef`&&(Z.query.limit||Z.query.offset),ft=nt.type===`func`||bt.type===`func`;if(!it&&!ft){const T=et===`main`?M:l;m.add(T);const B=et===`main`?k:I,Q=ol(b,et===`main`?bt:nt,X),ot=Q.collection,st=Q.path[0];st&&$c(st,Q.path,ot);const mt=B.pipe(Z_(Ut=>{const wt=j[T]||T,an=g[wt];if(!an)throw new Ox(wt,T,X.id,Object.keys(g));if(an.hasLoadedInitialState())return;const $e=Ut.getInner().map(([[Te]])=>Te),Ps=new Oe(Q.path);an.requestSnapshot({where:CT(Ps,$e),optimizedOnly:!0})||an.requestSnapshot()}));et===`main`?k=mt:I=mt}}return k.pipe(Xv(I,t.type),RA(t.type))}function AA(n,t,i,r){const l=i.filter(d=>d!==r),o=Od(n),u=Od(t);if(o&&l.includes(o)&&u===r)return{mainExpr:n,joinedExpr:t};if(o===r&&u&&l.includes(u))return{mainExpr:t,joinedExpr:n};throw!o||!u?new mx:o===u?new yx(o):l.includes(o)?u!==r?new vx(r):new bx:new Sx(o)}function Od(n){switch(n.type){case`ref`:return n.path[0]||null;case`func`:{const t=new Set;for(const i of n.args){const r=Od(i);r&&t.add(r)}return t.size===1?Array.from(t)[0]:null}default:return null}}function OA(n,t,i,r,l,o,u,d,p,g,y,m,v,w){switch(n.type){case`collectionRef`:{const b=t[n.alias];if(!b)throw new Nv(n.alias,n.collection.id,Object.keys(t));return m[n.alias]=n.collection.id,{alias:n.alias,input:b,collectionId:n.collection.id}}case`queryRef`:{const b=g.get(n.query)||n.query,E=y(b,t,i,r,l,o,u,d,p,g);Object.assign(m,E.aliasToCollectionId),Object.assign(v,E.aliasRemapping);const _=g.has(n.query),j=n.query.from.alias;if(!(!_&&n.alias===j))for(const[q,K]of E.sourceWhereClauses)w.set(q,K);const A=Object.keys(E.aliasToCollectionId).find(q=>E.aliasToCollectionId[q]===E.collectionId);A&&A!==n.alias&&(v[n.alias]=A);const G=E.pipeline.pipe(le(q=>{const[K,[W,et]]=q;return[K,W]}));return{alias:n.alias,input:G,collectionId:E.collectionId}}default:throw new wx(n.type)}}function RA(n){return function(t){return t.pipe(ps(i=>{const[r,[l,o]]=i,u=l?.[1],d=o?.[1];return n===`inner`?!!(u&&d):n===`left`?!!u:n===`right`?!!d:!0}),le(i=>{const[r,[l,o]]=i,u=l?.[0],d=l?.[1],p=o?.[0],g=o?.[1],y={};return d&&Object.assign(y,d),g&&Object.assign(y,g),[`[${u},${p}]`,y]}))}}function DA(n,t,i){switch(n){case`left`:return{activeSource:`main`,lazySource:i};case`right`:return{activeSource:`joined`,lazySource:t};case`inner`:return t.sizeUA(l,r)))}function NA(n){return n.type===`agg`}function jA(n){return n&&typeof n==`object`&&!Br(n)}function ib(n,t,i){for(const[r,l]of Object.entries(t)){if(r.startsWith(`__SPREAD_SENTINEL__`)){const u=r.slice(19),d=u.lastIndexOf(`__`),p=d>=0?u.slice(0,d):u,g=l&&typeof l==`object`&&`type`in l&&l.type===`ref`;if(p.includes(`.`)||g){const y=[...n],m=g?l:new Oe(p.split(`.`)),v=ue(m);i.push({kind:`merge`,targetPath:y,source:v})}else{const y=p,m=[...n];i.push({kind:`merge`,targetPath:m,source:v=>v[y]})}continue}const o=l;if(o&&o.type===`includesSubquery`){i.push({kind:`field`,alias:[...n,r].join(`.`),compiled:()=>null});continue}if(jA(o)){ib([...n,r],o,i);continue}if(NA(o)||Lr(o))i.push({kind:`field`,alias:[...n,r].join(`.`),compiled:()=>null});else{if(o===void 0||!Br(o)){i.push({kind:`field`,alias:[...n,r].join(`.`),compiled:()=>o});continue}if(o instanceof Ue){const u=o.value;i.push({kind:`field`,alias:[...n,r].join(`.`),compiled:()=>u})}else i.push({kind:`field`,alias:[...n,r].join(`.`),compiled:ue(o)})}}}const Or=Symbol(`includesRouting`);function Ac(n,t,i,r,l,o,u,d,p=new WeakMap,g=new WeakMap,y,m){const v=p.get(n);if(v)return v;Dd(n);const{optimizedQuery:w,sourceWhereClauses:b}=fA(n);let E=w;g.set(E,n),kd(E,n,g);const _={...t},j={},O={},A={},{alias:M,input:G,collectionId:q}=LA(E.from,_,i,r,l,o,u,d,p,g,j,O,b);A[M]=G;let K=G;if(y&&m){const dt=m.path.slice(1);K=G.pipe(le(([Z,it])=>[KA(it,dt),[Z,it]])).pipe(Xv(y,`inner`)).pipe(ps(([Z,[it]])=>it!=null),le(([Z,[it,ft]])=>{const[T,B]=it,Y={...B,__correlationKey:Z};return ft!=null&&(Y.__parentContext=ft),[ft!=null?`${String(T)}::${JSON.stringify(ft)}`:T,Y]})),A[M]=K}let W=K.pipe(le(([dt,k])=>{const{__parentContext:I,...Z}=k,it={[M]:Z};return I&&(Object.assign(it,I),it.__parentContext=I),[dt,it]}));if(E.join&&E.join.length>0&&(W=_A(W,E.join,A,q,M,_,p,g,i,r,l,o,u,d,n,Ac,j,O,b)),E.where&&E.where.length>0)for(const dt of E.where){const k=Wd(dt),I=ue(k);W=W.pipe(ps(([Z,it])=>Ar(I(it))))}if(E.fnWhere&&E.fnWhere.length>0)for(const dt of E.fnWhere)W=W.pipe(ps(([k,I])=>Ar(dt(I))));const et=[],X=[];if(E.select){const dt=HA(E.select);dt.length>0&&(E={...E,select:{...E.select}});for(const{key:k,subquery:I}of dt){const Z=ue(I.correlationField);let it;if(I.parentProjection&&I.parentProjection.length>0){const B=I.parentProjection.map(Y=>({alias:Y.path[0],field:Y.path.slice(1),compiled:ue(Y)}));it=W.pipe(le(([Y,Q])=>{const ot={};for(const st of B){ot[st.alias]||(ot[st.alias]={});const mt=st.compiled(Q);let Ut=ot[st.alias];for(let wt=0;wt[Z(Y),null]));it=it.pipe($v(B=>B.map(([Y,Q])=>[Y,Q>0?1:0])));const ft=I.parentFilters&&I.parentFilters.length>0?{...I.query,where:[...I.query.where||[],...I.parentFilters]}:I.query,T=Ac(ft,_,i,r,l,o,u,d,p,g,it,I.childCorrelationField);if(Object.assign(j,T.aliasToCollectionId),Object.assign(O,T.aliasRemapping),et.push({pipeline:T.pipeline,fieldName:I.fieldName,correlationField:I.correlationField,childCorrelationField:I.childCorrelationField,hasOrderBy:!!(I.query.orderBy&&I.query.orderBy.length>0),childCompilationResult:T,parentProjection:I.parentProjection,materialization:I.materialization,scalarField:I.scalarField}),I.parentProjection&&I.parentProjection.length>0){const B=I.parentProjection.map(Q=>({alias:Q.path[0],field:Q.path.slice(1),compiled:ue(Q)})),Y=Z;X.push({fieldName:I.fieldName,getRouting:Q=>{const ot={};for(const st of B){ot[st.alias]||(ot[st.alias]={});const mt=st.compiled(Q);let Ut=ot[st.alias];for(let wt=0;wt({correlationKey:Z(B),parentContext:null})});qA(E.select,k)}}if(E.distinct&&!E.fnSelect&&!E.select)throw new rx;if(E.fnSelect&&E.groupBy&&E.groupBy.length>0)throw new ax;E.fnSelect?W=W.pipe(le(([dt,k])=>{const I=E.fnSelect(k);return[dt,{...k,$selected:I}]})):E.select?W=zA(W,E.select):W=W.pipe(le(([dt,k])=>{const I=!E.join&&!E.groupBy?k[M]:k;return[dt,{...k,$selected:I}]})),X.length>0&&(W=W.pipe(le(([dt,k])=>{const I={};for(const{fieldName:Z,getRouting:it}of X)I[Z]=it(k);return k.$selected[Or]=I,[dt,k]})));const at=y?M:void 0;if(E.groupBy&&E.groupBy.length>0?W=yS(W,E.groupBy,E.having,E.select,E.fnHaving,q,at):E.select&&Object.values(E.select).some(k=>k.type===`agg`||Lr(k))&&(W=yS(W,[],E.having,E.select,E.fnHaving,q,at)),E.having&&(!E.groupBy||E.groupBy.length===0)&&!(E.select?Object.values(E.select).some(k=>k.type===`agg`):!1))throw new ox;if(E.fnHaving&&E.fnHaving.length>0&&(!E.groupBy||E.groupBy.length===0))for(const dt of E.fnHaving)W=W.pipe(ps(([k,I])=>dt(I)));if(E.distinct&&(W=W.pipe(H_(([dt,k])=>k.$selected))),E.orderBy&&E.orderBy.length>0){const dt=y&&(E.limit!==void 0||E.offset!==void 0)?(ft,T)=>{const B=T?.[M]?.__correlationKey,Y=T?.__parentContext;return Y!=null?JSON.stringify([B,Y]):B}:void 0,Z=yT(n,W,E.orderBy,E.select||{},i[q],u,d,E.limit,E.offset,dt).pipe(le(([ft,[T,B]])=>{const Y=T.$selected,Q=_S(Md(Y),T);if(y){const ot=T[M]?.__correlationKey,st=T.__parentContext??null;return delete Q.__correlationKey,delete Q.__parentContext,[ft,[Q,B,ot,st]]}return[ft,[Q,B]]})),it={collectionId:q,pipeline:Z,sourceWhereClauses:b,aliasToCollectionId:j,aliasRemapping:O,includes:et.length>0?et:void 0};return p.set(n,it),it}else if(E.limit!==void 0||E.offset!==void 0)throw new cx;const bt=W.pipe(le(([dt,k])=>{const I=k.$selected,Z=_S(Md(I),k);if(y){const it=k[M]?.__correlationKey,ft=k.__parentContext??null;return delete Z.__correlationKey,delete Z.__parentContext,[dt,[Z,void 0,it,ft]]}return[dt,[Z,void 0]]})),Lt={collectionId:q,pipeline:bt,sourceWhereClauses:b,aliasToCollectionId:j,aliasRemapping:O,includes:et.length>0?et:void 0};return p.set(n,Lt),Lt}function BA(n){const t=new Set;if(n.from.type===`collectionRef`&&t.add(n.from.alias),n.join)for(const i of n.join)i.from.type===`collectionRef`&&t.add(i.from.alias);return t}function Dd(n,t=new Set){const i=BA(n);for(const l of i)if(t.has(l))throw new ux(l,Array.from(t));const r=new Set([...t,...i]);if(n.from.type===`queryRef`&&Dd(n.from.query,r),n.join)for(const l of n.join)l.from.type===`queryRef`&&Dd(l.from.query,r)}function LA(n,t,i,r,l,o,u,d,p,g,y,m,v){switch(n.type){case`collectionRef`:{const w=t[n.alias];if(!w)throw new Nv(n.alias,n.collection.id,Object.keys(t));return y[n.alias]=n.collection.id,{alias:n.alias,input:w,collectionId:n.collection.id}}case`queryRef`:{const w=g.get(n.query)||n.query,b=Ac(w,t,i,r,l,o,u,d,p,g);Object.assign(y,b.aliasToCollectionId),Object.assign(m,b.aliasRemapping);const E=g.has(n.query),_=n.query.from.alias;if(!(!E&&n.alias===_))for(const[G,q]of b.sourceWhereClauses)v.set(G,q);const O=Object.keys(b.aliasToCollectionId).find(G=>b.aliasToCollectionId[G]===b.collectionId);O&&O!==n.alias&&(m[n.alias]=O);const M=b.pipeline.pipe(le(G=>{const[q,[K,W]]=G,et=Md(K);return[q,et]}));return{alias:n.alias,input:M,collectionId:b.collectionId}}default:throw new fx(n.type)}}function IA(n){return n instanceof Ue||n&&typeof n==`object`&&`type`in n&&n.type===`val`}function Md(n){return IA(n)?n.value:n}function _S(n,t){if(!n||typeof n!=`object`)return n;let i=!1;for(const r of pd)if(n[r]==null&&r in t){i=!0;break}if(!i)return n;for(const r of pd)n[r]==null&&r in t&&(n[r]=t[r]);return n}function kd(n,t,i){if(n.from.type===`queryRef`&&t.from.type===`queryRef`&&(i.set(n.from.query,t.from.query),kd(n.from.query,t.from.query,i)),n.join&&t.join)for(let r=0;r1)return new Oe(r.slice(1));if(r.length===1&&r[0]!==void 0)return new Oe([r[0]])}return new Oe(Array.isArray(r)?r:[String(r)])}else{const r=[];for(const l of n.args){const o=hp(l,t);r.push(o)}return new Ve(n.name,r)}}function dp(n,t){return n.map(r=>{const l=hp(r.expression,t);return{...r,expression:l}})}const lb=new WeakMap;function VA(n){return n.utils?.[rp]?.getBuilder?.()}function $A(n,t){lb.set(n,t)}function GA(n){return lb.get(n)}class Zt{constructor(t={}){this.query={},this.query={...t}}_createRefForSource(t,i){let r;try{r=Object.keys(t)}catch{const d=t===null?`null`:`undefined`;throw new Qo(i,d)}if(Array.isArray(t))throw new Qo(i,`array`);if(r.length!==1)throw r.length===0?new Qo(i,`empty object`):r.every(d=>!isNaN(Number(d)))?new Qo(i,`string`):new tx(i);const l=r[0],o=t[l];let u;if(o instanceof cp)u=new jr(o,l);else if(o instanceof Zt){const d=o._getQuery();if(!d.from)throw new ex(i);u=new Sn(d,l)}else throw new nx(l);return[l,u]}from(t){const[,i]=this._createRefForSource(t,`from clause`);return new Zt({...this.query,from:i})}join(t,i,r=`left`){const[l,o]=this._createRefForSource(t,`join clause`),d=[...this._getCurrentAliases(),l],p=vi(d),g=i(p);let y,m;if(g.type===`func`&&g.name===`eq`&&g.args.length===2)y=g.args[0],m=g.args[1];else throw new sx;const v={from:o,type:r,left:y,right:m},w=this.query.join||[];return new Zt({...this.query,join:[...w,v]})}leftJoin(t,i){return this.join(t,i,`left`)}rightJoin(t,i){return this.join(t,i,`right`)}innerJoin(t,i){return this.join(t,i,`inner`)}fullJoin(t,i){return this.join(t,i,`full`)}where(t){const i=this._getCurrentAliases(),r=vi(i),l=t(r),o=oc(l)?ne(l):l;if(!Br(o))throw new tS(TS(o));const u=this.query.where||[];return new Zt({...this.query,where:[...u,o]})}having(t){const i=this._getCurrentAliases(),r=this.query.select||this.query.fnSelect?bS(i):vi(i),l=t(r),o=oc(l)?ne(l):l;if(!Br(o))throw new tS(TS(o));const u=this.query.having||[];return new Zt({...this.query,having:[...u,o]})}select(t){const i=this._getCurrentAliases(),r=vi(i);let l=t(r);oc(l)&&l.__path.length===1&&(l={[`__SPREAD_SENTINEL__${l.__path[0]}__0`]:!0});const o=cb(l,i);return new Zt({...this.query,select:o,fnSelect:void 0})}orderBy(t,i=`asc`){const r=this._getCurrentAliases(),l=this.query.select||this.query.fnSelect?bS(r):vi(r),o=t(l),u=typeof i==`string`?{direction:i,nulls:`first`}:{direction:i.direction??`asc`,nulls:i.nulls??`first`,stringSort:i.stringSort,locale:i.stringSort===`locale`?i.locale:void 0,localeOptions:i.stringSort===`locale`?i.localeOptions:void 0},d=y=>({expression:ne(y),compareOptions:u}),p=Array.isArray(o)?o.map(y=>d(y)):[d(o)],g=this.query.orderBy||[];return new Zt({...this.query,orderBy:[...g,...p]})}groupBy(t){const i=this._getCurrentAliases(),r=vi(i),l=t(r),o=Array.isArray(l)?l.map(d=>ne(d)):[ne(l)],u=this.query.groupBy||[];return new Zt({...this.query,groupBy:[...u,...o]})}limit(t){return new Zt({...this.query,limit:t})}offset(t){return new Zt({...this.query,offset:t})}distinct(){return new Zt({...this.query,distinct:!0})}findOne(){return new Zt({...this.query,singleResult:!0})}_getCurrentAliases(){const t=[];if(this.query.from&&t.push(this.query.from.alias),this.query.join)for(const i of this.query.join)t.push(i.from.alias);return t}get fn(){const t=this;return{select(i){return new Zt({...t.query,select:void 0,fnSelect:i})},where(i){return new Zt({...t.query,fnWhere:[...t.query.fnWhere||[],i]})},having(i){return new Zt({...t.query,fnHaving:[...t.query.fnHaving||[],i]})}}}_getQuery(){if(!this.query.from)throw new ix;return this.query}}function TS(n){return n===null?`null`:n===void 0?`undefined`:typeof n==`object`?`object`:typeof n}function YA(n){return n===void 0?ne(null):n instanceof zv||n instanceof Ve||n instanceof Oe||n instanceof Ue?n:ne(n)}function ob(n){return n!==null&&typeof n==`object`&&!Br(n)&&!n.__refProxy}function cb(n,t=[]){if(!ob(n))return YA(n);const i={};for(const[r,l]of Object.entries(n)){if(typeof r==`string`&&r.startsWith(`__SPREAD_SENTINEL__`)){i[r]=l;continue}if(l instanceof Zt){i[r]=qh(l,r,t,`collection`);continue}if(l instanceof xT){if(!(l.query instanceof Zt))throw new Error(`toArray() must wrap a subquery builder`);i[r]=qh(l.query,r,t,`array`);continue}if(l instanceof _T){if(!(l.query instanceof Zt))throw new Error(`concat(toArray(...)) must wrap a subquery builder`);i[r]=qh(l.query,r,t,`concat`);continue}i[r]=cb(l,t)}return i}function pp(n){const t=[];switch(n.type){case`ref`:t.push(n);break;case`func`:for(const i of n.args??[])t.push(...pp(i));break}return t}function FA(n,t){const i=typeof n==`object`&&`expression`in n?n.expression:n;return pp(i).some(r=>r.path[0]!=null&&t.includes(r.path[0]))}function qh(n,t,i,r){const l=n._getQuery(),o=[l.from.alias];if(l.join)for(const A of l.join)o.push(A.from.alias);let u,d,p=-1,g=-1;if(l.where)for(let A=0;A=2){for(let q=0;q eq(child.parentId, parent.id))`);const y=[...l.where];if(g>=0){const A=y[p],G=(typeof A==`object`&&`expression`in A?A.expression:A).args.filter((q,K)=>K!==g);if(G.length===1){const q=typeof A==`object`&&`expression`in A&&A.residual;y[p]=q?{expression:G[0],residual:!0}:G[0]}else{const q=new Ve(`and`,G),K=typeof A==`object`&&`expression`in A&&A.residual;y[p]=K?{expression:q,residual:!0}:q}}else y.splice(p,1);const m=[],v=[];for(const A of y)FA(A,i)?v.push(A):m.push(A);let w;if(v.length>0){const A=new Set;w=[];for(const M of v){const G=typeof M==`object`&&`expression`in M?M.expression:M;for(const q of pp(G))q.path[0]!=null&&i.includes(q.path[0])&&!A.has(q.path.join(`.`))&&(A.add(q.path.join(`.`)),w.push(q))}}const b={...l,where:m.length>0?m:void 0},E=b.select,_=E===void 0||ob(E);let j=b,O;if(r===`concat`&&(E===void 0||_))throw new Error(`concat(toArray(...)) for "${t}" requires the subquery to select a scalar value`);if(!_){if(r===`collection`)throw new Error(`Includes subquery for "${t}" must select an object when materializing as a Collection`);O=xC,j={...b,select:{[O]:E}}}return new Ti(j,u,d,t,v.length>0?v:void 0,w,r,O)}function AS(n,t,i,r){if(n.type===`ref`&&t.type===`ref`){const l=n.path[0],o=t.path[0];if(l&&o&&i.includes(l)&&r.includes(o))return{parentRef:n,childRef:t};if(l&&o&&i.includes(o)&&r.includes(l))return{parentRef:t,childRef:n}}}function QA(n){const t=n(new Zt);return ub(t)}function ub(n){return n._getQuery()}function XA(n){const t={};function i(o){o.type===`collectionRef`?t[o.collection.id]=o.collection:o.type===`queryRef`&&r(o.query)}function r(o){if(o.from&&i(o.from),o.join&&Array.isArray(o.join))for(const u of o.join)u.from&&i(u.from);o.select&&l(o.select)}function l(o){for(const[u,d]of Object.entries(o))typeof u==`string`&&u.startsWith(`__SPREAD_SENTINEL__`)||(d instanceof Ti?r(d.query):gp(d)&&l(d))}return r(n),t}function fb(n){const t=n.from;if(t.type===`collectionRef`)return t.collection;if(t.type===`queryRef`)return fb(t.query);throw new Error(`Failed to extract collection. Invalid FROM clause: ${JSON.stringify(n)}`)}function JA(n){const t=new Map;function i(o){if(o)if(o.type===`collectionRef`){const{id:u}=o.collection,d=t.get(u);d?d.add(o.alias):t.set(u,new Set([o.alias]))}else o.type===`queryRef`&&l(o.query)}function r(o){for(const[u,d]of Object.entries(o))typeof u==`string`&&u.startsWith(`__SPREAD_SENTINEL__`)||(d instanceof Ti?l(d.query):gp(d)&&r(d))}function l(o){if(o){if(i(o.from),o.join)for(const u of o.join)i(u.from);o.select&&r(o.select)}}return l(n),t}function gp(n){return!(n===null||typeof n!=`object`||n instanceof Ti||`type`in n&&typeof n.type==`string`||n.__refProxy)}function ZA(n){const t=typeof n.query==`function`?QA(n.query):ub(n.query);if(t.select&&!gp(t.select))throw new lx;return t}function WA(n,t,i){const r=[];for(const l of t){const o=i(l.value);l.type===`insert`?r.push([[o,l.value],1]):l.type===`update`?(r.push([[o,l.previousValue],-1]),r.push([[o,l.value],1])):r.push([[o,l.value],-1])}return r.length!==0&&n.sendData(new ee(r)),r.length}function*PA(n){for(const t of n)t.type===`update`?(yield{type:`delete`,key:t.key,value:t.previousValue},yield{type:`insert`,key:t.key,value:t.value}):yield t}function tO(n,t){const i=[];for(const r of n){if(r.type===`insert`){if(t.has(r.key))continue;t.add(r.key)}else r.type===`delete`&&t.delete(r.key);i.push(r)}return i}function eO(n,t,i,r){let l=t,o=!1;for(const u of n){if(u.type===`delete`)continue;const d=!i.has(u.key);l===void 0||r(l,u.value)<0?(l=u.value,o=!0):d&&(o=!0)}return{biggest:l,shouldResetLoadKey:o}}function nO(n,t){const{orderBy:i,limit:r,offset:l}=n,o=r!==void 0&&l!==void 0?r+l:r,u=i?dp(i,t):void 0,d=u?.every(p=>{const g=p.expression;if(g.type!==`ref`)return!1;const y=g.path;return Array.isArray(y)&&y.length===1})??!1;return{orderBy:d?u:void 0,limit:d?o:void 0}}function sO(n,t,i,r,l){const{orderBy:o,valueExtractorForRawRow:u,offset:d}=n,p=t?u(t):void 0;let g;p!==void 0&&(g=Array.isArray(p)?p:[p]);const y=cl({minValues:g??null,offset:d,limit:l});if(i===y)return;const m=dp(o,r);return{minValues:g,normalizedOrderBy:m,loadRequestKey:y}}const OS=Symbol.for(`@tanstack/db.collection-config-builder`);class iO{constructor(t,i,r,l){this.alias=t,this.collectionId=i,this.collection=r,this.collectionConfigBuilder=l,this.biggest=void 0,this.subscriptionLoadingPromises=new Map,this.sentToD2Keys=new Set}subscribe(){const t=this.getWhereClauseForAlias();if(t){const i=hp(t,this.alias);return this.subscribeToChanges(i)}return this.subscribeToChanges()}subscribeToChanges(t){const i=this.getOrderByInfo(),r=d=>{d instanceof Promise&&this.collectionConfigBuilder.liveQueryCollection._sync.trackLoadPromise(d)},l=d=>{const p=d.subscription;if(d.status===`loadingSubset`)this.ensureLoadingPromise(p);else{const g=this.subscriptionLoadingPromises.get(p);g&&(this.subscriptionLoadingPromises.delete(p),g.resolve())}};let o;if(i)o=this.subscribeToOrderedChanges(t,i,l,r);else{const d=!this.collectionConfigBuilder.isLazyAlias(this.alias);o=this.subscribeToMatchingChanges(t,d,l)}o.status===`loadingSubset`&&this.ensureLoadingPromise(o);const u=()=>{const d=this.subscriptionLoadingPromises.get(o);d&&(this.subscriptionLoadingPromises.delete(o),d.resolve()),o.unsubscribe()};return this.collectionConfigBuilder.currentSyncState.unsubscribeCallbacks.add(u),o}sendChangesToPipeline(t,i){const r=Array.isArray(t)?t:[...t],l=tO(r,this.sentToD2Keys),o=this.collectionConfigBuilder.currentSyncState.inputs[this.alias],d=WA(o,l,this.collection.config.getKey)>0?i:void 0;this.collectionConfigBuilder.scheduleGraphRun(d,{alias:this.alias})}subscribeToMatchingChanges(t,i,r){const l=p=>{this.sendChangesToPipeline(p)},o=nO(this.collectionConfigBuilder.query,this.alias),u=i?p=>{p instanceof Promise&&this.collectionConfigBuilder.liveQueryCollection._sync.trackLoadPromise(p)}:void 0;return this.collection.subscribeChanges(l,{...i&&{includeInitialState:i},whereExpression:t,onStatusChange:r,orderBy:o.orderBy,limit:o.limit,onLoadSubsetResult:u})}subscribeToOrderedChanges(t,i,r,l){const{orderBy:o,offset:u,limit:d,index:p}=i,g=E=>{E instanceof Promise&&(this.pendingOrderedLoadPromise=E,E.finally(()=>{this.pendingOrderedLoadPromise===E&&(this.pendingOrderedLoadPromise=void 0)})),l(E)};this.orderedLoadSubsetResult=g;const y={},m=E=>{const _=Array.isArray(E)?E:[...E];this.trackSentValues(_,i.comparator);const j=PA(_);this.sendChangesToPipelineWithTracking(j,y.current)},v=this.collection.subscribeChanges(m,{whereExpression:t,onStatusChange:r});y.current=v;const w=this.collection.on(`truncate`,()=>{this.biggest=void 0,this.lastLoadRequestKey=void 0,this.pendingOrderedLoadPromise=void 0,this.sentToD2Keys.clear()});v.on(`unsubscribed`,()=>{w()});const b=dp(o,this.alias);return p?(v.setOrderByIndex(p),v.requestLimitedSnapshot({limit:u+d,orderBy:b,trackLoadSubsetPromise:!1,onLoadSubsetResult:g})):v.requestSnapshot({orderBy:b,limit:u+d,trackLoadSubsetPromise:!1,onLoadSubsetResult:g}),v}loadMoreIfNeeded(t){const i=this.getOrderByInfo();if(!i)return!0;const{dataNeeded:r}=i;if(!r||this.pendingOrderedLoadPromise)return!0;const l=r();return l>0&&this.loadNextItems(l,t),!0}sendChangesToPipelineWithTracking(t,i){if(!this.getOrderByInfo()){this.sendChangesToPipeline(t);return}const l=i;l[OS]??=this.loadMoreIfNeeded.bind(this,i),this.sendChangesToPipeline(t,l[OS])}loadNextItems(t,i){const r=this.getOrderByInfo();if(!r)return;const l=sO(r,this.biggest,this.lastLoadRequestKey,this.alias,t);l&&(this.lastLoadRequestKey=l.loadRequestKey,i.requestLimitedSnapshot({orderBy:l.normalizedOrderBy,limit:t,minValues:l.minValues,trackLoadSubsetPromise:!1,onLoadSubsetResult:this.orderedLoadSubsetResult}))}getWhereClauseForAlias(){const t=this.collectionConfigBuilder.sourceWhereClausesCache;if(t)return t.get(this.alias)}getOrderByInfo(){const t=this.collectionConfigBuilder.optimizableOrderByCollections[this.collectionId];if(t&&t.alias===this.alias)return t}trackSentValues(t,i){const r=eO(t,this.biggest,this.sentToD2Keys,i);this.biggest=r.biggest,r.shouldResetLoadKey&&(this.lastLoadRequestKey=void 0)}ensureLoadingPromise(t){if(this.subscriptionLoadingPromises.has(t))return;let i;const r=new Promise(l=>{i=l});this.subscriptionLoadingPromises.set(t,{resolve:i}),this.collectionConfigBuilder.liveQueryCollection._sync.trackLoadPromise(r)}}let rO=0;class aO{constructor(t){this.config=t,this.compiledAliasToCollectionId={},this.resultKeys=new WeakMap,this.orderByIndices=new WeakMap,this.isGraphRunning=!1,this.runCount=0,this.isInErrorState=!1,this.aliasDependencies={},this.builderDependencies=new Set,this.pendingGraphRuns=new Map,this.subscriptions={},this.lazySourcesCallbacks={},this.lazySources=new Set,this.optimizableOrderByCollections={},this.id=t.id||`live-query-${++rO}`,this.query=ZA({query:t.query}),this.collections=XA(this.query);const i=JA(this.query);this.collectionByAlias={};for(const[r,l]of i.entries()){const o=this.collections[r];if(o)for(const u of l)this.collectionByAlias[u]=o}this.query.orderBy&&this.query.orderBy.length>0&&(this.compare=hb(this.orderByIndices)),this.compareOptions=this.config.defaultStringCollation??fb(this.query).compareOptions,this.compileBasePipeline()}hasJoins(t){return!!(t.join&&t.join.length>0||t.from.type===`queryRef`&&this.hasJoins(t.from.query))}getConfig(){return{id:this.id,getKey:this.config.getKey||(t=>this.resultKeys.get(t)),sync:this.getSyncConfig(),compare:this.compare,defaultStringCollation:this.compareOptions,gcTime:this.config.gcTime||5e3,schema:this.config.schema,onInsert:this.config.onInsert,onUpdate:this.config.onUpdate,onDelete:this.config.onDelete,startSync:this.config.startSync,singleResult:this.query.singleResult,utils:{getRunCount:this.getRunCount.bind(this),setWindow:this.setWindow.bind(this),getWindow:this.getWindow.bind(this),[rp]:{getBuilder:()=>this,hasCustomGetKey:!!this.config.getKey,hasJoins:this.hasJoins(this.query),hasDistinct:!!this.query.distinct}}}}setWindow(t){if(!this.windowFn)throw new Dx;return this.currentWindow=t,this.windowFn(t),this.maybeRunGraphFn?.(),this.liveQueryCollection?.isLoadingSubset?new Promise(i=>{const r=this.liveQueryCollection.on(`loadingSubset:change`,l=>{l.isLoadingSubset||(r(),i())})}):!0}getWindow(){if(!(!this.windowFn||!this.currentWindow))return{offset:this.currentWindow.offset??0,limit:this.currentWindow.limit??0}}getCollectionIdForAlias(t){const i=this.compiledAliasToCollectionId[t];if(i)return i;const r=this.collectionByAlias[t];if(r)return r.id;throw new Error(`Unknown source alias "${t}"`)}isLazyAlias(t){return this.lazySources.has(t)}maybeRunGraph(t){if(!this.isGraphRunning){if(!this.currentSyncConfig||!this.currentSyncState)throw new Error(`maybeRunGraph called without active sync session. This should not happen.`);this.isGraphRunning=!0;try{const{begin:i,commit:r}=this.currentSyncConfig,l=this.currentSyncState;if(this.isInErrorState)return;if(l.subscribedToAllCollections){let o=!1;for(;l.graph.pendingWork();)l.graph.run(),l.flushPendingChanges?.(),t?.(),o=!0;o||t?.(),l.messagesCount===0&&(i(),r()),this.updateLiveQueryStatus(this.currentSyncConfig)}}finally{this.isGraphRunning=!1}}}scheduleGraphRun(t,i){const r=i?.contextId??uc()?.id,l=i?.jobId??this,o=(()=>{if(i?.dependencies)return i.dependencies;const p=new Set(this.builderDependencies);if(i?.alias){const g=this.aliasDependencies[i.alias];if(g)for(const y of g)p.add(y)}return p.delete(this),Array.from(p)})();if(r)for(const p of o)typeof p.scheduleGraphRun==`function`&&p.scheduleGraphRun(void 0,{contextId:r});if(!this.currentSyncConfig||!this.currentSyncState)throw new Error(`scheduleGraphRun called without active sync session. This should not happen.`);let u=r?this.pendingGraphRuns.get(r):void 0;u||(u={loadCallbacks:new Set},r&&this.pendingGraphRuns.set(r,u)),t&&u.loadCallbacks.add(t);const d=r?void 0:u;xc.schedule({contextId:r,jobId:l,dependencies:o,run:()=>this.executeGraphRun(r,d)})}clearPendingGraphRun(t){this.pendingGraphRuns.delete(t)}hasPendingGraphRun(t){return this.pendingGraphRuns.has(t)}executeGraphRun(t,i){const r=i??(t?this.pendingGraphRuns.get(t):void 0);if(t&&this.pendingGraphRuns.delete(t),!r||!this.currentSyncConfig||!this.currentSyncState)return;this.incrementRunCount();const l=()=>{let o=!0,u;if(r.loadCallbacks.forEach(d=>{try{o=d()&&o}catch(p){o=!1,u??=p}}),u)throw u;return o};this.maybeRunGraph(l)}getSyncConfig(){return{rowUpdateMode:`full`,sync:this.syncFn.bind(this)}}incrementRunCount(){this.runCount++}getRunCount(){return this.runCount}syncFn(t){this.liveQueryCollection=t.collection,this.currentSyncConfig=t;const i={messagesCount:0,subscribedToAllCollections:!1,unsubscribeCallbacks:new Set},r=this.extendPipelineWithChangeProcessing(t,i);this.currentSyncState=r,this.unsubscribeFromSchedulerClears=xc.onClear(u=>{this.clearPendingGraphRun(u)});const l=t.collection.on(`loadingSubset:change`,u=>{u.isLoadingSubset||this.updateLiveQueryStatus(t)});i.unsubscribeCallbacks.add(l);const o=this.subscribeToAllCollections(t,r);return this.maybeRunGraphFn=()=>this.scheduleGraphRun(o),this.scheduleGraphRun(o),()=>{i.unsubscribeCallbacks.forEach(u=>u()),this.currentSyncConfig=void 0,this.currentSyncState=void 0,this.pendingGraphRuns.clear(),this.graphCache=void 0,this.inputsCache=void 0,this.pipelineCache=void 0,this.sourceWhereClausesCache=void 0,this.includesCache=void 0,this.lazySources.clear(),this.optimizableOrderByCollections={},this.lazySourcesCallbacks={},Object.keys(this.subscriptions).forEach(u=>delete this.subscriptions[u]),this.compiledAliasToCollectionId={},this.unsubscribeFromSchedulerClears?.(),this.unsubscribeFromSchedulerClears=void 0}}compileBasePipeline(){this.graphCache=new N_,this.inputsCache=Object.fromEntries(Object.keys(this.collectionByAlias).map(r=>[r,this.graphCache.newInput()]));const t=Ac(this.query,this.inputsCache,this.collections,this.subscriptions,this.lazySourcesCallbacks,this.lazySources,this.optimizableOrderByCollections,r=>{this.windowFn=r});this.pipelineCache=t.pipeline,this.sourceWhereClausesCache=t.sourceWhereClauses,this.compiledAliasToCollectionId=t.aliasToCollectionId,this.includesCache=t.includes;const i=Object.keys(this.compiledAliasToCollectionId).filter(r=>!Object.hasOwn(this.inputsCache,r));if(i.length>0)throw new Rx(i)}maybeCompileBasePipeline(){return(!this.graphCache||!this.inputsCache||!this.pipelineCache)&&this.compileBasePipeline(),{graph:this.graphCache,inputs:this.inputsCache,pipeline:this.pipelineCache}}extendPipelineWithChangeProcessing(t,i){const{begin:r,commit:l}=t,{graph:o,inputs:u,pipeline:d}=this.maybeCompileBasePipeline();let p=new Map;d.pipe(md(y=>{const m=y.getInner();i.messagesCount+=m.length,m.reduce(dO,p)}));const g=this.setupIncludesOutput(this.includesCache,i);return i.flushPendingChanges=()=>{const y=p.size>0,m=fO(g);if(!y&&!m)return;let v=p;if(this.config.getKey){const w=new Map;for(const[,b]of p){const E=this.config.getKey(b.value),_=w.get(E);_?(_.inserts+=b.inserts,_.deletes+=b.deletes,b.inserts>0&&(_.value=b.value,b.orderByIndex!==void 0&&(_.orderByIndex=b.orderByIndex))):w.set(E,{...b})}v=w}y&&(r(),v.forEach(this.applyChanges.bind(this,t)),l()),p=new Map,Ud(g,t.collection,this.id,y?v:null,t)},o.finalize(),i.graph=o,i.inputs=u,i.pipeline=d,i}setupIncludesOutput(t,i){return!t||t.length===0?[]:t.map(r=>{const l={fieldName:r.fieldName,childCorrelationField:r.childCorrelationField,hasOrderBy:r.hasOrderBy,materialization:r.materialization,scalarField:r.scalarField,childRegistry:new Map,pendingChildChanges:new Map,correlationToParentKeys:new Map};return r.pipeline.pipe(md(o=>{const u=o.getInner();i.messagesCount+=u.length;for(const[[d,p],g]of u){const[y,m,v,w]=p,b=Ir(v,w);let E=l.pendingChildChanges.get(b);E||(E=new Map,l.pendingChildChanges.set(b,E));const _=E.get(d)||{deletes:0,inserts:0,value:y,orderByIndex:m};g<0?_.deletes+=Math.abs(g):g>0&&(_.inserts+=g,_.value=y),E.set(d,_)}})),r.childCompilationResult.includes&&(l.nestedSetups=db(r.childCompilationResult.includes,i),l.nestedRoutingIndex=new Map,l.nestedRoutingReverseIndex=new Map),l})}applyChanges(t,i,r){const{write:l,collection:o}=t,{deletes:u,inserts:d,value:p,orderByIndex:g}=i;if(this.resultKeys.set(p,r),g!==void 0&&this.orderByIndices.set(p,g),d&&u===0)l({value:p,type:`insert`});else if(d>u||d===u&&o.has(o.getKeyFromItem(p)))l({value:p,type:`update`});else if(u>0)l({value:p,type:`delete`});else throw new Error(`Could not apply changes: ${JSON.stringify(i)}. This should never happen.`)}handleSourceStatusChange(t,i,r){const{status:l}=r;if(l===`error`){this.transitionToError(`Source collection '${i}' entered error state`);return}if(l===`cleaned-up`){this.transitionToError(`Source collection '${i}' was manually cleaned up while live query '${this.id}' depends on it. Live queries prevent automatic GC, so this was likely a manual cleanup() call.`);return}this.updateLiveQueryStatus(t)}updateLiveQueryStatus(t){const{markReady:i}=t;if(this.isInErrorState)return;const r=this.currentSyncState?.subscribedToAllCollections,l=this.allCollectionsReady(),o=this.liveQueryCollection?.isLoadingSubset;r&&l&&!o&&i()}transitionToError(t){this.isInErrorState=!0,console.error(`[Live Query Error] ${t}`),this.liveQueryCollection?._lifecycle.setStatus(`error`)}allCollectionsReady(){return Object.values(this.collections).every(t=>t.isReady())}subscribeToAllCollections(t,i){const r=Object.entries(this.compiledAliasToCollectionId);if(r.length===0)throw new Error(`Compiler returned no alias metadata for query '${this.id}'. This should not happen; please report.`);const l=r.map(([u,d])=>{const p=this.collectionByAlias[u]??this.collections[d],g=GA(p);g&&g!==this?(this.aliasDependencies[u]=[g],this.builderDependencies.add(g)):this.aliasDependencies[u]=[];const y=new iO(u,d,p,this),m=p.on(`status:change`,b=>{this.handleSourceStatusChange(t,d,b)});i.unsubscribeCallbacks.add(m);const v=y.subscribe();return this.subscriptions[u]=v,y.loadMoreIfNeeded.bind(y,v)}),o=()=>(l.map(u=>u()),!0);return i.subscribedToAllCollections=!0,o}}function hb(n){return(t,i)=>{const r=n.get(t),l=n.get(i);return r&&l?rl?1:0:0}}function RS(n){return n.materialization!==`collection`}function DS(n,t){if(!t)return n.materialization===`array`?[]:n.materialization===`concat`?``:void 0;if(n.materialization===`collection`)return t.collection;const i=[...t.collection.toArray],r=n.scalarField?i.map(l=>l?.[n.scalarField]):i;return n.materialization===`array`?r:r.map(l=>String(l??``)).join(``)}function db(n,t){return n.map(i=>{const r=new Map;i.pipeline.pipe(md(o=>{const u=o.getInner();t.messagesCount+=u.length;for(const[[d,p],g]of u){const[y,m,v,w]=p,b=Ir(v,w);let E=r.get(b);E||(E=new Map,r.set(b,E));const _=E.get(d)||{deletes:0,inserts:0,value:y,orderByIndex:m};g<0?_.deletes+=Math.abs(g):g>0&&(_.inserts+=g,_.value=y),E.set(d,_)}}));const l={compilationResult:i,buffer:r};return i.childCompilationResult.includes&&(l.nestedSetups=db(i.childCompilationResult.includes,t)),l})}function lO(n){return n.map(t=>{const i={fieldName:t.compilationResult.fieldName,childCorrelationField:t.compilationResult.childCorrelationField,hasOrderBy:t.compilationResult.hasOrderBy,materialization:t.compilationResult.materialization,scalarField:t.compilationResult.scalarField,childRegistry:new Map,pendingChildChanges:new Map,correlationToParentKeys:new Map};return t.nestedSetups&&(i.nestedSetups=t.nestedSetups,i.nestedRoutingIndex=new Map,i.nestedRoutingReverseIndex=new Map),i})}function oO(n){const t=new Set;if(!n.nestedSetups)return t;for(let i=0;i0&&(w.value=m.value,m.orderByIndex!==void 0&&(w.orderByIndex=m.orderByIndex))):v.set(y,{...m})}t.add(d),l.push(o)}for(const o of l)r.buffer.delete(o)}return t}function cO(n,t,i){if(n.nestedSetups){for(const r of n.nestedSetups)for(const[,l]of i)if(l.inserts>0){const o=l.value[Or]?.[r.compilationResult.fieldName],u=o?.correlationKey,d=o?.parentContext??null,p=Ir(u,d);if(u!=null){n.nestedRoutingIndex.set(p,t);let g=n.nestedRoutingReverseIndex.get(t);g||(g=new Set,n.nestedRoutingReverseIndex.set(t,g)),g.add(p)}}else if(l.deletes>0&&l.inserts===0){const o=l.value[Or]?.[r.compilationResult.fieldName],u=o?.correlationKey,d=o?.parentContext??null,p=Ir(u,d);if(u!=null){n.nestedRoutingIndex.delete(p);const g=n.nestedRoutingReverseIndex.get(t);g&&(g.delete(p),g.size===0&&n.nestedRoutingReverseIndex.delete(t))}}}}function uO(n,t){if(!n.nestedRoutingReverseIndex)return;const i=n.nestedRoutingReverseIndex.get(t);if(i){for(const r of i)n.nestedRoutingIndex.delete(r);n.nestedRoutingReverseIndex.delete(t)}}function pb(n){for(const t of n)if(t.buffer.size>0||t.nestedSetups&&pb(t.nestedSetups))return!0;return!1}function Ir(n,t){return t==null?n:JSON.stringify([n,t])}function MS(n,t,i,r,l){const o=new WeakMap,u=r?new WeakMap:null;let d=null;const p=u?hb(u):void 0,y={collection:op({id:`__child-collection:${n}-${t}-${cl(i)}`,getKey:m=>o.get(m),compare:p,sync:{rowUpdateMode:`full`,sync:m=>(d=m,()=>{d=null})},startSync:!0}),get syncMethods(){return d},resultKeys:o,orderByIndices:u};return l&&(y.includesStates=lO(l)),y}function Ud(n,t,i,r,l){for(const o of n){if(r){for(const[y,m]of r)if(m.inserts>0){const v=m.value,w=v[Or]?.[o.fieldName],b=w?.correlationKey,E=w?.parentContext??null,_=Ir(b,E);if(b!=null){if(!o.childRegistry.has(_)){const M=MS(i,o.fieldName,_,o.hasOrderBy,o.nestedSetups);o.childRegistry.set(_,M)}let j=o.correlationToParentKeys.get(_);j||(j=new Set,o.correlationToParentKeys.set(_,j)),j.add(y);const O=DS(o,o.childRegistry.get(_));v[o.fieldName]=O;const A=t.get(y);A&&A!==v&&(A[o.fieldName]=O)}}}const u=RS(o)?new Set(o.pendingChildChanges.keys()):null,d=new Map;if(o.pendingChildChanges.size>0){for(const[y,m]of o.pendingChildChanges){let v=o.childRegistry.get(y);if(v||(v=MS(i,o.fieldName,y,o.hasOrderBy,o.nestedSetups),o.childRegistry.set(y,v)),o.materialization===`collection`&&hO(t,o.fieldName,y,o.correlationToParentKeys,v.collection),v.syncMethods){v.syncMethods.begin();for(const[w,b]of m)v.resultKeys.set(b.value,w),v.orderByIndices&&b.orderByIndex!==void 0&&v.orderByIndices.set(b.value,b.orderByIndex),b.inserts>0&&b.deletes===0?v.syncMethods.write({value:b.value,type:`insert`}):b.inserts>b.deletes||b.inserts===b.deletes&&v.syncMethods.collection.has(v.syncMethods.collection.getKeyFromItem(b.value))?v.syncMethods.write({value:b.value,type:`update`}):b.deletes>0&&v.syncMethods.write({value:b.value,type:`delete`});v.syncMethods.commit()}cO(o,y,m),d.set(y,{entry:v,childChanges:m})}o.pendingChildChanges.clear()}const p=oO(o);for(const[,{entry:y,childChanges:m}]of d)y.includesStates&&Ud(y.includesStates,y.collection,y.collection.id,m,y.syncMethods);for(const y of p){if(d.has(y))continue;const m=o.childRegistry.get(y);m?.includesStates&&Ud(m.includesStates,m.collection,m.collection.id,null,m.syncMethods)}const g=RS(o)?new Set([...u||[],...p]):null;if(l&&g&&g.size>0){const y=[];for(const m of g){const v=o.correlationToParentKeys.get(m);if(!v)continue;const w=o.childRegistry.get(m);for(const b of v){const E=t.get(b);if(E){const _=l.collection.getKeyFromItem(E),j={...E};E[o.fieldName]=DS(o,w),y.push({type:`update`,key:_,value:E,previousValue:j})}}}y.length>0&&t._changes.emitEvents(y,!0)}if(r){for(const[y,m]of r)if(m.deletes>0&&m.inserts===0){const v=m.value[Or]?.[o.fieldName],w=v?.correlationKey,b=v?.parentContext??null,E=Ir(w,b);if(w!=null){const _=o.correlationToParentKeys.get(E);_&&(_.delete(y),_.size===0&&(uO(o,E),o.childRegistry.delete(E),o.correlationToParentKeys.delete(E)))}}}}if(r)for(const[,o]of r)delete o.value[Or]}function fO(n){for(const t of n)if(t.pendingChildChanges.size>0||t.nestedSetups&&pb(t.nestedSetups))return!0;return!1}function hO(n,t,i,r,l){const o=r.get(i);if(o)for(const u of o){const d=n.get(u);d&&(d[t]=l)}}function dO(n,[[t,i],r]){const[l,o]=i,u=n.get(t)||{deletes:0,inserts:0,value:l,orderByIndex:o};return r<0?u.deletes+=Math.abs(r):r>0&&(u.inserts+=r,u.value=l,o!==void 0&&(u.orderByIndex=o)),n.set(t,u),n}function kS(n){return new aO(n).getConfig()}function Kh(n){if(typeof n==`function`){const i=kS({query:n});return US(i)}else{const t=n,i=kS(t);return t.utils&&(i.utils={...i.utils,...t.utils}),US(i)}}function US(n){const t=op(n),i=VA(n);return i&&$A(t,i),t}var Zo={exports:{}},Vh,zS;function pO(){if(zS)return Vh;zS=1;function n(t){var i=new t,r=i;function l(){var u=i;return u.next?i=u.next:(i=new t,r=i),u.next=null,u}function o(u){r.next=u,r=u}return{get:l,release:o}}return Vh=n,Vh}var NS;function gO(){if(NS)return Zo.exports;NS=1;var n=pO();function t(o,u,d){if(typeof o==`function`&&(d=u,u=o,o=null),!(d>=1))throw new Error(`fastqueue concurrency must be equal to or greater than 1`);var p=n(r),g=null,y=null,m=0,v=null,w={push:M,drain:i,saturated:i,pause:E,paused:!1,get concurrency(){return d},set concurrency(X){if(!(X>=1))throw new Error(`fastqueue concurrency must be equal to or greater than 1`);if(d=X,!w.paused)for(;g&&m=d||w.paused?y?(y.next=nt,y=nt):(g=nt,y=nt,w.saturated()):(m++,u.call(o,nt.value,nt.worked))}function G(X,at){var nt=p.get();nt.context=o,nt.release=q,nt.value=X,nt.callback=at||i,nt.errorHandler=v,m>=d||w.paused?g?(nt.next=g,g=nt):(g=nt,y=nt,w.saturated()):(m++,u.call(o,nt.value,nt.worked))}function q(X){X&&p.release(X);var at=g;at&&m<=d?w.paused?m--:(y===g&&(y=null),g=at.next,at.next=null,u.call(o,at.value,at.worked),y===null&&w.empty()):--m===0&&w.drain()}function K(){g=null,y=null,w.drain=i}function W(){g=null,y=null,w.drain(),w.drain=i}function et(X){v=X}}function i(){}function r(){this.value=null,this.callback=i,this.next=null,this.release=i,this.context=null,this.errorHandler=null;var o=this;this.worked=function(d,p){var g=o.callback,y=o.errorHandler,m=o.value;o.value=null,o.callback=i,o.errorHandler&&y(d,m),g.call(o.context,d,p),o.release(o)}}function l(o,u,d){typeof o==`function`&&(d=u,u=o,o=null);function p(E,_){u.call(this,E).then(function(j){_(null,j)},_)}var g=t(o,p,d),y=g.push,m=g.unshift;return g.push=v,g.unshift=w,g.drained=b,g;function v(E){var _=new Promise(function(j,O){y(E,function(A,M){if(A){O(A);return}j(M)})});return _.catch(i),_}function w(E){var _=new Promise(function(j,O){m(E,function(A,M){if(A){O(A);return}j(M)})});return _.catch(i),_}function b(){var E=new Promise(function(_){process.nextTick(function(){if(g.idle())_();else{var j=g.drain;g.drain=function(){typeof j==`function`&&j(),_(),g.drain=j}}})});return E}}return Zo.exports=t,Zo.exports.promise=l,Zo.exports}var yO=gO();const gb=fC(yO),Tn=`Stream-Next-Offset`,Gc=`Stream-Cursor`,Yc=`Stream-Up-To-Date`,Ln=`Stream-Closed`,$h=`Stream-Seq`,mO=`Stream-TTL`,SO=`Stream-Expires-At`,jS=`Producer-Id`,Wo=`Producer-Epoch`,BS=`Producer-Seq`,vO=`Producer-Expected-Seq`,bO=`Producer-Received-Seq`,Gh=`offset`,Po=`live`,wO=`stream-sse-data-encoding`;var Js=class yb extends Error{status;text;json;headers;constructor(t,i,r,l,o,u){super(u||`HTTP Error ${t} at ${o}: ${i??JSON.stringify(r)}`),this.url=o,this.name=`FetchError`,this.status=t,this.text=i,this.json=r,this.headers=l}static async fromResponse(t,i){const r=t.status,l=Object.fromEntries([...t.headers.entries()]);let o,u;const d=t.headers.get(`content-type`);if(!t.bodyUsed&&t.body!==null)if(d&&d.includes(`application/json`))try{u=await t.json()}catch{o=await t.text()}else o=await t.text();return new yb(r,o,u,l,i)}},yp=class extends Error{constructor(){super(`Fetch with backoff aborted`),this.name=`FetchBackoffAbortError`}},Wt=class zd extends Error{status;code;details;constructor(t,i,r,l){super(t),this.name=`DurableStreamError`,this.code=i,this.status=r,this.details=l}static async fromResponse(t,i){const r=t.status;let l;const o=t.headers.get(`content-type`);if(!t.bodyUsed&&t.body!==null)if(o&&o.includes(`application/json`))try{l=await t.json()}catch{l=await t.text()}else l=await t.text();const u=LS(r),d=`Durable stream error at ${i}: ${t.statusText||r}`;return new zd(d,u,r,l)}static fromFetchError(t){const i=LS(t.status);return new zd(t.message,i,t.status,t.json??t.text)}};function LS(n){switch(n){case 400:return`BAD_REQUEST`;case 401:return`UNAUTHORIZED`;case 403:return`FORBIDDEN`;case 404:return`NOT_FOUND`;case 409:return`CONFLICT_SEQ`;case 429:return`RATE_LIMITED`;case 503:return`BUSY`;default:return`UNKNOWN`}}var EO=class extends Error{constructor(){super(`Invalid stream options: missing required url parameter`),this.name=`MissingStreamUrlError`}},mb=class extends Wt{code=`STREAM_CLOSED`;status=409;streamClosed=!0;finalOffset;constructor(n,t){super(`Cannot append to closed stream`,`STREAM_CLOSED`,409,n),this.name=`StreamClosedError`,this.finalOffset=t}},CO=class extends Error{constructor(){super(`Invalid signal option. It must be an instance of AbortSignal.`),this.name=`InvalidSignalError`}};const xO=[429,503],mp={initialDelay:100,maxDelay:6e4,multiplier:1.3,maxRetries:1/0};function _O(n){if(!n)return 0;const t=Number(n);if(Number.isFinite(t)&&t>0)return t*1e3;const i=Date.parse(n);if(!isNaN(i)){const r=i-Date.now();return Math.max(0,Math.min(r,36e5))}return 0}function Sb(n,t=mp){const{initialDelay:i,maxDelay:r,multiplier:l,debug:o=!1,onFailedAttempt:u,maxRetries:d=1/0}=t;return async(...p)=>{const g=p[0],y=p[1];let m=i,v=0;for(;;)try{const w=await n(...p);if(w.ok)return w;throw await Js.fromResponse(w,g.toString())}catch(w){if(u?.(),y?.signal?.aborted)throw new yp;if(w instanceof Js&&!xO.includes(w.status)&&w.status>=400&&w.status<500)throw w;{if(v++,v>d)throw o&&console.log(`Max retries reached (${v}/${d}), giving up`),w;const b=w instanceof Js?_O(w.headers[`retry-after`]):0,E=Math.random()*m,_=Math.min(E,r),j=Math.max(b,_);if(o){const O=b>0?`server+client`:`client`;console.log(`Retry attempt #${v} after ${j}ms (${O}, serverMin=${b}ms, clientBackoff=${_}ms)`)}await new Promise(O=>setTimeout(O,j)),m=Math.min(m*l,r)}}}}const TO=[201,204,205];function AO(n){return async(...t)=>{const i=t[0],r=await n(...t);try{if(r.status<200||TO.includes(r.status))return r;const l=await r.arrayBuffer();return new Response(l,{status:r.status,statusText:r.statusText,headers:r.headers})}catch(l){throw t[1]?.signal?.aborted?new yp:new Js(r.status,void 0,void 0,Object.fromEntries([...r.headers.entries()]),i.toString(),l instanceof Error?l.message:typeof l==`string`?l:`failed to read body`)}}}function OO(n){return typeof Symbol<`u`&&typeof Symbol.asyncIterator==`symbol`&&typeof n[Symbol.asyncIterator]==`function`}function RO(n){if(typeof Symbol>`u`||typeof Symbol.asyncIterator!=`symbol`||typeof n[Symbol.asyncIterator]==`function`)return;const t=function(){const i=this.getReader();let r=!1,l=0;return{async next(){if(r)return{done:!0,value:void 0};l++;try{const{value:u,done:d}=await i.read();return d?(r=!0,i.releaseLock(),{done:!0,value:void 0}):{done:!1,value:u}}catch(u){r=!0;try{i.releaseLock()}catch{}throw u}finally{l--}},async return(u){if(l>0)throw new TypeError(`Cannot close a readable stream reader when it has pending read requests`);r=!0;const d=i.cancel(u);return i.releaseLock(),await d,{done:!0,value:void 0}},async throw(u){if(l>0)throw new TypeError(`Cannot close a readable stream reader when it has pending read requests`);r=!0;const d=i.cancel(u);throw i.releaseLock(),await d,u},[Symbol.asyncIterator](){return this}}};try{Object.defineProperty(n,Symbol.asyncIterator,{configurable:!0,writable:!0,value:t})}catch{return}try{Object.defineProperty(n,`values`,{configurable:!0,writable:!0,value:t})}catch{}}function Yh(n){return OO(n)||RO(n),n}async function*IS(n,t){const i=n.getReader(),r=new TextDecoder;let l=``,o={data:[]};try{for(;!t?.aborted;){const{done:d,value:p}=await i.read();if(d)break;l+=r.decode(p,{stream:!0}),l=l.replace(/\r\n/g,` +`).replace(/\r/g,` +`);const g=l.split(` +`);l=g.pop()??``;for(const y of g)if(y===``){if(o.type&&o.data.length>0){const m=o.data.join(` +`);if(o.type===`data`)yield{type:`data`,data:m};else if(o.type===`control`)try{const v=JSON.parse(m);yield{type:`control`,streamNextOffset:v.streamNextOffset,streamCursor:v.streamCursor,upToDate:v.upToDate,streamClosed:v.streamClosed}}catch(v){const w=m.length>100?m.slice(0,100)+`...`:m;throw new Wt(`Failed to parse SSE control event: ${v instanceof Error?v.message:String(v)}. Data: ${w}`,`PARSE_ERROR`)}}o={data:[]}}else if(y.startsWith(`event:`)){const m=y.slice(6);o.type=m.startsWith(` `)?m.slice(1):m}else if(y.startsWith(`data:`)){const m=y.slice(5);o.data.push(m.startsWith(` `)?m.slice(1):m)}}const u=r.decode();if(u&&(l+=u),l&&o.type&&o.data.length>0){const d=o.data.join(` +`);if(o.type===`data`)yield{type:`data`,data:d};else if(o.type===`control`)try{const p=JSON.parse(d);yield{type:`control`,streamNextOffset:p.streamNextOffset,streamCursor:p.streamCursor,upToDate:p.upToDate,streamClosed:p.streamClosed}}catch(p){const g=d.length>100?d.slice(0,100)+`...`:d;throw new Wt(`Failed to parse SSE control event: ${p instanceof Error?p.message:String(p)}. Data: ${g}`,`PARSE_ERROR`)}}}finally{i.releaseLock()}}var Sp=class{shouldContinueLive(n,t){return!(n&&this.upToDate||t===!1||this.streamClosed)}},vb=class Nd extends Sp{offset;cursor;upToDate;streamClosed;constructor(t){super(),this.offset=t.offset,this.cursor=t.cursor,this.upToDate=t.upToDate,this.streamClosed=t.streamClosed}shouldUseSse(){return!1}withResponseMetadata(t){return new Nd({offset:t.offset??this.offset,cursor:t.cursor??this.cursor,upToDate:t.upToDate,streamClosed:this.streamClosed||t.streamClosed})}withSSEControl(t){const i=this.streamClosed||(t.streamClosed??!1);return new Nd({offset:t.streamNextOffset,cursor:t.streamCursor||this.cursor,upToDate:t.streamClosed??!1?!0:t.upToDate??this.upToDate,streamClosed:i})}pause(){return new vp(this)}},Fh=class Er extends Sp{offset;cursor;upToDate;streamClosed;consecutiveShortConnections;connectionStartTime;constructor(t){super(),this.offset=t.offset,this.cursor=t.cursor,this.upToDate=t.upToDate,this.streamClosed=t.streamClosed,this.consecutiveShortConnections=t.consecutiveShortConnections??0,this.connectionStartTime=t.connectionStartTime}shouldUseSse(){return!0}withResponseMetadata(t){return new Er({offset:t.offset??this.offset,cursor:t.cursor??this.cursor,upToDate:t.upToDate,streamClosed:this.streamClosed||t.streamClosed,consecutiveShortConnections:this.consecutiveShortConnections,connectionStartTime:this.connectionStartTime})}withSSEControl(t){const i=this.streamClosed||(t.streamClosed??!1);return new Er({offset:t.streamNextOffset,cursor:t.streamCursor||this.cursor,upToDate:t.streamClosed??!1?!0:t.upToDate??this.upToDate,streamClosed:i,consecutiveShortConnections:this.consecutiveShortConnections,connectionStartTime:this.connectionStartTime})}startConnection(t){return new Er({offset:this.offset,cursor:this.cursor,upToDate:this.upToDate,streamClosed:this.streamClosed,consecutiveShortConnections:this.consecutiveShortConnections,connectionStartTime:t})}handleConnectionEnd(t,i,r){if(this.connectionStartTime===void 0)return{action:`healthy`,state:this};const l=t-this.connectionStartTime;if(l=r.maxShortConnections?{action:`fallback`,state:new vb({offset:this.offset,cursor:this.cursor,upToDate:this.upToDate,streamClosed:this.streamClosed})}:{action:`reconnect`,state:new Er({offset:this.offset,cursor:this.cursor,upToDate:this.upToDate,streamClosed:this.streamClosed,consecutiveShortConnections:o,connectionStartTime:this.connectionStartTime}),backoffAttempt:o}}return l>=r.minConnectionDuration?{action:`healthy`,state:new Er({offset:this.offset,cursor:this.cursor,upToDate:this.upToDate,streamClosed:this.streamClosed,consecutiveShortConnections:0,connectionStartTime:this.connectionStartTime})}:{action:`healthy`,state:this}}pause(){return new vp(this)}},vp=class jd extends Sp{#t;constructor(t){super(),this.#t=t}get offset(){return this.#t.offset}get cursor(){return this.#t.cursor}get upToDate(){return this.#t.upToDate}get streamClosed(){return this.#t.streamClosed}shouldUseSse(){return this.#t.shouldUseSse()}withResponseMetadata(t){const i=this.#t.withResponseMetadata(t);return new jd(i)}withSSEControl(t){const i=this.#t.withSSEControl(t);return new jd(i)}pause(){return this}resume(){return{state:this.#t,justResumed:!0}}};const HS=`PAUSE_STREAM`;var DO=class{url;contentType;live;startOffset;#t;#e;#n;#s;#a;#i;#c;#l;#p;#d;#h;#f;#g;#y=!1;#x=null;#o=`active`;#u;#w;#m;#S;#v;#E;#O;constructor(n){this.url=n.url,this.contentType=n.contentType,this.live=n.live,this.startOffset=n.startOffset;const t={offset:n.initialOffset,cursor:n.initialCursor,upToDate:n.initialUpToDate,streamClosed:n.initialStreamClosed};this.#i=n.startSSE?new Fh(t):new vb(t),this.#t=n.firstResponse.headers,this.#e=n.firstResponse.status,this.#n=n.firstResponse.statusText,this.#s=n.firstResponse.ok,this.#a=!1,this.#c=n.isJsonMode,this.#l=n.abortController,this.#p=n.fetchNext,this.#d=n.startSSE,this.#v={minConnectionDuration:n.sseResilience?.minConnectionDuration??1e3,maxShortConnections:n.sseResilience?.maxShortConnections??3,backoffBaseDelay:n.sseResilience?.backoffBaseDelay??100,backoffMaxDelay:n.sseResilience?.backoffMaxDelay??5e3,logWarnings:n.sseResilience?.logWarnings??!0},this.#E=n.encoding,this.#g=new Promise((i,r)=>{this.#h=i,this.#f=r}),this.#O=this.#I(n.firstResponse),this.#l.signal.addEventListener(`abort`,()=>{this.#u?.abort(this.#l.signal.reason),this.#S?.(),this.#m=void 0,this.#S=void 0},{once:!0}),this.#R()}#R(){if(typeof document==`object`&&typeof document.hidden==`boolean`&&typeof document.addEventListener==`function`){const n=()=>{document.hidden?this.#D():this.#T()};document.addEventListener(`visibilitychange`,n),this.#w=()=>{typeof document==`object`&&document.removeEventListener(`visibilitychange`,n)},document.hidden&&this.#D()}}#D(){this.#o===`active`&&(this.#o=`pause-requested`,this.#i=this.#i.pause(),this.#m=new Promise(n=>{this.#S=n}),this.#u?.abort(HS))}#T(){if(this.#o===`paused`||this.#o===`pause-requested`){if(this.#l.signal.aborted)return;this.#i instanceof vp&&(this.#i=this.#i.resume().state),this.#o=`active`,this.#S?.(),this.#m=void 0,this.#S=void 0}}get headers(){return this.#t}get status(){return this.#e}get statusText(){return this.#n}get ok(){return this.#s}get isLoading(){return this.#a}get offset(){return this.#i.offset}get cursor(){return this.#i.cursor}get upToDate(){return this.#i.upToDate}get streamClosed(){return this.#i.streamClosed}#A(){if(!this.#c)throw new Wt(`JSON methods are only valid for JSON-mode streams. Content-Type is "${this.contentType}" and json hint was not set.`,`BAD_REQUEST`)}#r(){this.#w?.(),this.#h()}#_(n){this.#w?.(),this.#f(n)}#b(n){if(this.#x!==null)throw new Wt(`Cannot call ${n}() - this StreamResponse is already being consumed via ${this.#x}()`,`ALREADY_CONSUMED`);this.#x=n}#M(){return this.#i.shouldContinueLive(this.#y,this.live)}#j(n){this.#i=this.#i.withResponseMetadata({offset:n.headers.get(Tn)||void 0,cursor:n.headers.get(Gc)||void 0,upToDate:n.headers.has(Yc),streamClosed:n.headers.get(Ln)?.toLowerCase()===`true`}),this.#t=n.headers,this.#e=n.status,this.#n=n.statusText,this.#s=n.ok}#U(n){this.#i=this.#i.withSSEControl(n)}#z(){this.#i instanceof Fh||(this.#i=new Fh({offset:this.#i.offset,cursor:this.#i.cursor,upToDate:this.#i.upToDate,streamClosed:this.#i.streamClosed})),this.#i=this.#i.startConnection(Date.now())}async#k(){if(!this.#i.shouldUseSse()||!this.#M()||!this.#d)return null;const n=this.#i.handleConnectionEnd(Date.now(),this.#l.signal.aborted,this.#v);if(this.#i=n.state,n.action===`fallback`)return this.#v.logWarnings&&console.warn(`[Durable Streams] SSE connections are closing immediately (possibly due to proxy buffering or misconfiguration). Falling back to long polling. Your proxy must support streaming SSE responses (not buffer the complete response). Configuration: Nginx add 'X-Accel-Buffering: no', Caddy add 'flush_interval -1' to reverse_proxy.`),null;if(n.action===`reconnect`){const i=Math.min(this.#v.backoffMaxDelay,this.#v.backoffBaseDelay*Math.pow(2,n.backoffAttempt)),r=Math.floor(Math.random()*i);await new Promise(l=>setTimeout(l,r))}this.#z(),this.#u=new AbortController;const t=await this.#d(this.offset,this.cursor,this.#u.signal);return t.body?IS(t.body,this.#u.signal):null}async#B(n){const{done:t,value:i}=await n.next();if(t){try{const r=await this.#k();if(r)return{type:`continue`,newIterator:r}}catch(r){return{type:`error`,error:r instanceof Error?r:new Error(`SSE reconnection failed`)}}return{type:`closed`}}return i.type===`data`?this.#L(i.data,n):(this.#U(i),i.upToDate?{type:`response`,response:kO(``,i.streamNextOffset,i.streamCursor,!0,i.streamClosed??!1,this.contentType,this.#E)}:{type:`continue`})}async#L(n,t){const i=[n];for(;;){const{done:r,value:l}=await t.next();if(r){const o=Bd(i,this.offset,this.cursor,this.upToDate,this.streamClosed,this.contentType,this.#E,this.#c);try{const u=await this.#k();return{type:`response`,response:o,newIterator:u??void 0}}catch(u){return{type:`error`,error:u instanceof Error?u:new Error(`SSE reconnection failed`)}}}if(l.type===`control`)return this.#U(l),{type:`response`,response:Bd(i,l.streamNextOffset,l.streamCursor,l.upToDate??!1,l.streamClosed??!1,this.contentType,this.#E,this.#c)};i.push(l.data)}}#I(n){let t=!1,i=null;return new ReadableStream({pull:async r=>{try{if(!t)if(t=!0,(n.headers.get(`content-type`)?.includes(`text/event-stream`)??!1)&&n.body)this.#z(),this.#u=new AbortController,i=IS(n.body,this.#u.signal);else{if(r.enqueue(n),this.upToDate&&!this.#M()){this.#r(),r.close();return}return}if(i){if(this.#o===`pause-requested`||this.#o===`paused`){if(this.#o=`paused`,this.#m&&await this.#m,this.#l.signal.aborted){this.#r(),r.close();return}const l=await this.#k();if(l)i=l;else{this.#r(),r.close();return}}for(;;){const l=await this.#B(i);switch(l.type){case`response`:l.newIterator&&(i=l.newIterator),r.enqueue(l.response);return;case`closed`:this.#r(),r.close();return;case`error`:this.#_(l.error),r.error(l.error);return;case`continue`:l.newIterator&&(i=l.newIterator);continue}}}if(this.#M()){let l=!1;if(this.#o===`pause-requested`||this.#o===`paused`){if(this.#o=`paused`,this.#m&&await this.#m,this.#l.signal.aborted){this.#r(),r.close();return}l=!0}if(this.#l.signal.aborted){this.#r(),r.close();return}this.#u=new AbortController;const o=await this.#p(this.offset,this.cursor,this.#u.signal,l);this.#j(o),r.enqueue(o);return}this.#r(),r.close()}catch(l){if(this.#u?.signal.aborted&&this.#u.signal.reason===HS){this.#o===`pause-requested`&&(this.#o=`paused`);return}this.#l.signal.aborted?(this.#r(),r.close()):(this.#_(l instanceof Error?l:new Error(String(l))),r.error(l))}},cancel:()=>{this.#l.abort(),this.#w?.(),this.#r()}})}#C(){return this.#O.getReader()}async body(){this.#b(`body`),this.#y=!0;const n=this.#C(),t=[];try{let r=await n.read();for(;!r.done;){const l=this.upToDate,o=await r.value.blob();if(o.size>0&&t.push(o),l)break;r=await n.read()}}finally{n.releaseLock()}if(this.#r(),t.length===0)return new Uint8Array(0);if(t.length===1)return new Uint8Array(await t[0].arrayBuffer());const i=new Blob(t);return new Uint8Array(await i.arrayBuffer())}async json(){this.#b(`json`),this.#A(),this.#y=!0;const n=this.#C(),t=[];try{let i=await n.read();for(;!i.done;){const r=this.upToDate,o=(await i.value.text()).trim()||`[]`;let u;try{u=JSON.parse(o)}catch(d){const p=o.length>100?o.slice(0,100)+`...`:o;throw new Wt(`Failed to parse JSON response: ${d instanceof Error?d.message:String(d)}. Data: ${p}`,`PARSE_ERROR`)}if(Array.isArray(u)?t.push(...u):t.push(u),r)break;i=await n.read()}}finally{n.releaseLock()}return this.#r(),t}async text(){this.#b(`text`),this.#y=!0;const n=this.#C(),t=[];try{let i=await n.read();for(;!i.done;){const r=this.upToDate,l=await i.value.text();if(l&&t.push(l),r)break;i=await n.read()}}finally{n.releaseLock()}return this.#r(),t.join(``)}#N(){const{readable:n,writable:t}=new TransformStream,i=this.#C();return(async()=>{try{let l=await i.read();for(;!l.done;){const o=this.upToDate,u=l.value.body;if(u&&await u.pipeTo(t,{preventClose:!0,preventAbort:!0,preventCancel:!0}),o&&!this.#M())break;l=await i.read()}await t.close(),this.#r()}catch(l){if(this.#l.signal.aborted){try{await t.close()}catch{}this.#r()}else{try{await t.abort(l)}catch{}this.#_(l instanceof Error?l:new Error(String(l)))}}finally{i.releaseLock()}})(),n}bodyStream(){return this.#b(`bodyStream`),Yh(this.#N())}jsonStream(){this.#b(`jsonStream`),this.#A();const n=this.#C();let t=[];const i=new ReadableStream({pull:async r=>{if(t.length>0){r.enqueue(t.shift());return}let l=await n.read();for(;!l.done;){const d=(await l.value.text()).trim()||`[]`;let p;try{p=JSON.parse(d)}catch(g){const y=d.length>100?d.slice(0,100)+`...`:d;throw new Wt(`Failed to parse JSON response: ${g instanceof Error?g.message:String(g)}. Data: ${y}`,`PARSE_ERROR`)}if(t=Array.isArray(p)?p:[p],t.length>0){r.enqueue(t.shift());return}l=await n.read()}this.#r(),r.close()},cancel:()=>{n.releaseLock(),this.cancel()}});return Yh(i)}textStream(){this.#b(`textStream`);const n=new TextDecoder,t=this.#N().pipeThrough(new TransformStream({transform(i,r){r.enqueue(n.decode(i,{stream:!0}))},flush(i){const r=n.decode();r&&i.enqueue(r)}}));return Yh(t)}subscribeJson(n){this.#b(`subscribeJson`),this.#A();const t=new AbortController,i=this.#C();return(async()=>{try{let l=await i.read();for(;!l.done&&!t.signal.aborted;){const o=l.value,{offset:u,cursor:d,upToDate:p,streamClosed:g}=Qh(o,this.offset,this.cursor,this.streamClosed),m=(await o.text()).trim()||`[]`;let v;try{v=JSON.parse(m)}catch(b){const E=m.length>100?m.slice(0,100)+`...`:m;throw new Wt(`Failed to parse JSON response: ${b instanceof Error?b.message:String(b)}. Data: ${E}`,`PARSE_ERROR`)}const w=Array.isArray(v)?v:[v];await n({items:w,offset:u,cursor:d,upToDate:p,streamClosed:g}),l=await i.read()}this.#r()}catch(l){const o=t.signal.aborted,u=l instanceof TypeError&&String(l).includes(`Body`);!o&&!u?this.#_(l instanceof Error?l:new Error(String(l))):this.#r()}finally{i.releaseLock()}})(),()=>{t.abort(),this.cancel()}}subscribeBytes(n){this.#b(`subscribeBytes`);const t=new AbortController,i=this.#C();return(async()=>{try{let l=await i.read();for(;!l.done&&!t.signal.aborted;){const o=l.value,{offset:u,cursor:d,upToDate:p,streamClosed:g}=Qh(o,this.offset,this.cursor,this.streamClosed),y=await o.arrayBuffer();await n({data:new Uint8Array(y),offset:u,cursor:d,upToDate:p,streamClosed:g}),l=await i.read()}this.#r()}catch(l){const o=t.signal.aborted,u=l instanceof TypeError&&String(l).includes(`Body`);!o&&!u?this.#_(l instanceof Error?l:new Error(String(l))):this.#r()}finally{i.releaseLock()}})(),()=>{t.abort(),this.cancel()}}subscribeText(n){this.#b(`subscribeText`);const t=new AbortController,i=this.#C();return(async()=>{try{let l=await i.read();for(;!l.done&&!t.signal.aborted;){const o=l.value,{offset:u,cursor:d,upToDate:p,streamClosed:g}=Qh(o,this.offset,this.cursor,this.streamClosed),y=await o.text();await n({text:y,offset:u,cursor:d,upToDate:p,streamClosed:g}),l=await i.read()}this.#r()}catch(l){const o=t.signal.aborted,u=l instanceof TypeError&&String(l).includes(`Body`);!o&&!u?this.#_(l instanceof Error?l:new Error(String(l))):this.#r()}finally{i.releaseLock()}})(),()=>{t.abort(),this.cancel()}}cancel(n){this.#l.abort(n),this.#w?.(),this.#r()}get closed(){return this.#g}};function Qh(n,t,i,r){const l=n.headers.get(Tn),o=n.headers.get(Gc),u=n.headers.has(Yc),d=n.headers.get(Ln)?.toLowerCase()===`true`;return{offset:l??t,cursor:o??i,upToDate:u,streamClosed:d||r}}function MO(n){const t=n.replace(/[\n\r]/g,``);if(t.length===0)return new Uint8Array(0);if(t.length%4!==0)throw new Wt(`Invalid base64 data: length ${t.length} is not a multiple of 4`,`PARSE_ERROR`);try{if(typeof Buffer<`u`)return new Uint8Array(Buffer.from(t,`base64`));{const i=atob(t),r=new Uint8Array(i.length);for(let l=0;lm.length>0).map(m=>MO(m));if(y.length===0)g=new ArrayBuffer(0);else if(y.length===1){const m=y[0];g=m.buffer.slice(m.byteOffset,m.byteOffset+m.byteLength)}else{const m=y.reduce((b,E)=>b+E.length,0),v=new Uint8Array(m);let w=0;for(const b of y)v.set(b,w),w+=b.length;g=v.buffer}}else if(d){const y=[];for(const m of n){const v=m.trim();if(v.length!==0)if(v.startsWith(`[`)&&v.endsWith(`]`)){const w=v.slice(1,-1).trim();w.length>0&&y.push(w)}else y.push(v)}g=`[${y.join(`,`)}]`}else g=n.join(``);return new Response(g,{status:200,headers:p})}async function nl(n){const t={};if(!n)return t;for(const[i,r]of Object.entries(n))typeof r==`function`?t[i]=await r():t[i]=r;return t}async function hs(n,t,i){const r=n.status;if(r===404)throw new Wt(`Stream not found: ${t}`,`NOT_FOUND`,404);if(r===409){if(n.headers.get(Ln)?.toLowerCase()===`true`){const d=n.headers.get(Tn)??void 0;throw new mb(t,d)}const o=i?.operation===`create`?`Stream already exists: ${t}`:`Sequence conflict: seq is lower than last appended`,u=i?.operation===`create`?`CONFLICT_EXISTS`:`CONFLICT_SEQ`;throw new Wt(o,u,409)}throw r===400?new Wt(`Bad request (possibly content-type mismatch)`,`BAD_REQUEST`,400):await Wt.fromResponse(n,t)}async function fc(n){const t={};if(!n)return t;for(const[i,r]of Object.entries(n))r!==void 0&&(typeof r==`function`?t[i]=await r():t[i]=r);return t}const qS=new Set;function UO(){if(!(typeof process>`u`))return`production`}function zO(){return typeof globalThis.window<`u`}function NO(){if(typeof globalThis.window<`u`&&typeof globalThis.window.location<`u`)return globalThis.window.location.href}function jO(n){try{return new URL(n)}catch{const t=NO();if(t)try{return new URL(n,t)}catch{return}return}}function bb(n,t){if(t===!1||UO()===`test`||!zO()||typeof console>`u`||typeof console.warn!=`function`)return;const r=n instanceof URL?n.toString():n,l=jO(r);l&&l.protocol===`http:`&&(qS.has(l.origin)||(qS.add(l.origin),console.warn(`[DurableStream] Using HTTP (not HTTPS) typically limits browsers to ~6 concurrent connections per origin under HTTP/1.1. This can cause slow streams and app freezes with multiple active streams. Use HTTPS for HTTP/2 support. See https://electric-sql.com/r/electric-http2 for more information.`)))}async function BO(n){if(!n.url)throw new Wt(`Invalid stream options: missing required url parameter`,`BAD_REQUEST`);let t=n.headers,i=n.params;for(;;)try{return await LO({...n,headers:t,params:i})}catch(r){if(n.onError){const l=await n.onError(r instanceof Error?r:new Error(String(r)));if(l===void 0)throw r;l.params&&(i={...i,...l.params}),l.headers&&(t={...t,...l.headers});continue}throw r}}async function LO(n){const t=n.url instanceof URL?n.url.toString():n.url;bb(t,n.warnOnHttp);const i=new URL(t),r=n.offset??`-1`;i.searchParams.set(Gh,r);const l=n.live??!0;(l===`long-poll`||l===`sse`)&&i.searchParams.set(Po,l);const o=await fc(n.params);for(const[q,K]of Object.entries(o))i.searchParams.set(q,K);const u=await nl(n.headers),d=new AbortController;n.signal&&n.signal.addEventListener(`abort`,()=>d.abort(n.signal?.reason),{once:!0});const p=n.fetch??((...q)=>fetch(...q)),g=n.backoffOptions??mp,y=Sb(p,g);let m;try{m=await y(i.toString(),{method:`GET`,headers:u,signal:d.signal})}catch(q){throw q instanceof yp?new Wt(`Stream request was aborted`,`UNKNOWN`):q}const v=m.headers.get(`content-type`)??void 0,w=m.headers.get(Tn)??r,b=m.headers.get(Gc)??void 0,E=m.headers.has(Yc),_=m.headers.get(Ln)?.toLowerCase()===`true`,j=n.json===!0||(v?.includes(`application/json`)??!1),A=m.headers.get(wO)===`base64`?`base64`:void 0,M=async(q,K,W,et)=>{const X=new URL(t);X.searchParams.set(Gh,q),et||(l===`sse`?X.searchParams.set(Po,`sse`):(l===!0||l===`long-poll`)&&X.searchParams.set(Po,`long-poll`)),K&&X.searchParams.set(`cursor`,K);const at=await fc(n.params);for(const[Lt,dt]of Object.entries(at))X.searchParams.set(Lt,dt);const nt=await nl(n.headers),bt=await y(X.toString(),{method:`GET`,headers:nt,signal:W});return bt.ok||await hs(bt,t),bt},G=l===`sse`?async(q,K,W)=>{const et=new URL(t);et.searchParams.set(Gh,q),et.searchParams.set(Po,`sse`),K&&et.searchParams.set(`cursor`,K);const X=await fc(n.params);for(const[bt,Lt]of Object.entries(X))et.searchParams.set(bt,Lt);const at=await nl(n.headers),nt=await y(et.toString(),{method:`GET`,headers:at,signal:W});return nt.ok||await hs(nt,t),nt}:void 0;return new DO({url:t,contentType:v,live:l,startOffset:r,isJsonMode:j,initialOffset:w,initialCursor:b,initialUpToDate:E,initialStreamClosed:_,firstResponse:m,abortController:d,fetchNext:M,startSSE:G,sseResilience:n.sseResilience,encoding:A})}var KS=class extends Error{currentEpoch;constructor(n){super(`Producer epoch is stale. Current server epoch: ${n}. Call restart() or create a new producer with a higher epoch.`),this.name=`StaleEpochError`,this.currentEpoch=n}},IO=class extends Error{expectedSeq;receivedSeq;constructor(n,t){super(`Producer sequence gap: expected ${n}, received ${t}`),this.name=`SequenceGapError`,this.expectedSeq=n,this.receivedSeq=t}};function VS(n){return n?n.split(`;`)[0].trim().toLowerCase():``}var wb=class{#t;#e;#n;#s=0;#a;#i;#c;#l;#p;#d;#h=[];#f=0;#g=null;#y;#x;#o=!1;#u=null;#w;#m;#S=new Map;constructor(n,t,i){const r=i?.epoch??0,l=i?.maxBatchBytes??1024*1024,o=i?.maxInFlight??5,u=i?.lingerMs??5;if(r<0)throw new Error(`epoch must be >= 0`);if(l<=0)throw new Error(`maxBatchBytes must be > 0`);if(o<=0)throw new Error(`maxInFlight must be > 0`);if(u<0)throw new Error(`lingerMs must be >= 0`);this.#t=n,this.#e=t,this.#n=r,this.#a=i?.autoClaim??!1,this.#i=l,this.#c=u,this.#p=i?.signal,this.#d=i?.onError,this.#l=i?.fetch??((...d)=>fetch(...d)),this.#x=o,this.#m=!this.#a,this.#y=gb.promise(this.#O.bind(this),this.#x),this.#p&&this.#p.addEventListener(`abort`,()=>{this.#A(new Wt(`Producer aborted`,`ALREADY_CLOSED`,void 0,void 0))},{once:!0})}append(n){if(this.#o)throw new Wt(`Producer is closed`,`ALREADY_CLOSED`,void 0,void 0);let t;if(typeof n==`string`)t=new TextEncoder().encode(n);else if(n instanceof Uint8Array)t=n;else throw new Wt(`append() requires string or Uint8Array. For objects, use JSON.stringify().`,`BAD_REQUEST`,400,void 0);this.#h.push({body:t}),this.#f+=t.length,this.#f>=this.#i?this.#E():this.#g||(this.#g=setTimeout(()=>{this.#g=null,this.#h.length>0&&this.#E()},this.#c))}async flush(){this.#g&&(clearTimeout(this.#g),this.#g=null),this.#h.length>0&&this.#E(),await this.#y.drained()}async detach(){if(!this.#o){this.#o=!0;try{await this.flush()}catch{}}}async close(n){if(this.#o){if(this.#u)return this.#u;await this.flush();const i=await this.#v(this.#w);return this.#u=i,i}this.#o=!0,this.#w=n,await this.flush();const t=await this.#v(n);return this.#u=t,t}async#v(n){const t=this.#t.contentType??`application/octet-stream`,i=VS(t)===`application/json`;let r;if(n!==void 0){const g=typeof n==`string`?new TextEncoder().encode(n):n;i?r=`[${new TextDecoder().decode(g)}]`:r=g}const l=this.#s,u={...await this.#t.resolveHeaders(),"content-type":t,[jS]:this.#e,[Wo]:this.#n.toString(),[BS]:l.toString(),[Ln]:`true`},d=await this.#l(this.#t.url,{method:`POST`,headers:u,body:r,signal:this.#p});if(d.status===204)return this.#s=l+1,{finalOffset:d.headers.get(Tn)??``};if(d.status===200)return this.#s=l+1,{finalOffset:d.headers.get(Tn)??``};if(d.status===403){const g=d.headers.get(Wo),y=g?parseInt(g,10):this.#n;if(this.#a){const m=y+1;return this.#n=m,this.#s=0,this.#v(n)}throw new KS(y)}throw await Js.fromResponse(d,this.#t.url)}async restart(){await this.flush(),this.#n++,this.#s=0}get epoch(){return this.#n}get nextSeq(){return this.#s}get pendingCount(){return this.#h.length}get inFlightCount(){return this.#y.length()}#E(){if(this.#h.length===0)return;const n=this.#h,t=this.#s;this.#h=[],this.#f=0,this.#s++,this.#a&&!this.#m&&this.#y.length()>0?this.#y.drained().then(()=>{this.#y.push({batch:n,seq:t}).catch(()=>{})}):this.#y.push({batch:n,seq:t}).catch(()=>{})}async#O(n){const{batch:t,seq:i}=n,r=this.#n;try{await this.#T(t,i,r),this.#m||(this.#m=!0),this.#R(r,i,void 0)}catch(l){throw this.#R(r,i,l),this.#d&&this.#d(l),l}}#R(n,t,i){let r=this.#S.get(n);r||(r=new Map,this.#S.set(n,r));const l=r.get(t);if(l){l.resolved=!0,l.error=i;for(const u of l.waiters)u(i);l.waiters=[]}else r.set(t,{resolved:!0,error:i,waiters:[]});const o=t-this.#x*3;if(o>0)for(const u of r.keys())u{const u=d=>{d?o(d):l()};r?r.waiters.push(u):i.set(t,{resolved:!1,waiters:[u]})})}async#T(n,t,i){const r=this.#t.contentType??`application/octet-stream`,l=VS(r)===`application/json`;let o;if(l)o=`[${n.map(v=>new TextDecoder().decode(v.body)).join(`,`)}]`;else{const m=n.reduce((b,E)=>b+E.body.length,0),v=new Uint8Array(m);let w=0;for(const b of n)v.set(b.body,w),w+=b.body.length;o=v}const u=this.#t.url,p={...await this.#t.resolveHeaders(),"content-type":r,[jS]:this.#e,[Wo]:i.toString(),[BS]:t.toString()},g=await this.#l(u,{method:`POST`,headers:p,body:o,signal:this.#p});if(g.status===204)return{offset:``,duplicate:!0};if(g.status===200)return{offset:g.headers.get(Tn)??``,duplicate:!1};if(g.status===403){const m=g.headers.get(Wo),v=m?parseInt(m,10):i;if(this.#a){const w=v+1;return this.#n=w,this.#s=1,this.#T(n,0,w)}throw new KS(v)}if(g.status===409){const m=g.headers.get(vO),v=m?parseInt(m,10):0;if(v0&&this.#d(n),this.#h=[],this.#f=0,this.#g&&(clearTimeout(this.#g),this.#g=null)}};function Xh(n){return n?n.split(`;`)[0].trim().toLowerCase():``}function HO(n){return n!=null&&typeof n.then==`function`}var Ys=class Wa{url;contentType;#t;#e;#n;#s;#a;#i;#c=[];constructor(t){VO(t);const i=t.url instanceof URL?t.url.toString():t.url;this.url=i,this.#t={...t,url:i},this.#s=t.onError,t.contentType&&(this.contentType=t.contentType),this.#a=t.batching!==!1,this.#a&&(this.#i=gb.promise(this.#d.bind(this),1)),this.#n=t.fetch??((...o)=>fetch(...o));const r={...t.backoffOptions??mp},l=Sb(this.#n,r);this.#e=AO(l)}static async create(t){const i=new Wa(t);return await i.create({contentType:t.contentType,ttlSeconds:t.ttlSeconds,expiresAt:t.expiresAt,body:t.body,closed:t.closed}),i}static async connect(t){const i=new Wa(t);return await i.head(),i}static async head(t){return new Wa(t).head()}static async delete(t){return new Wa(t).delete()}async head(t){const{requestHeaders:i,fetchUrl:r}=await this.#f(),l=await this.#n(r.toString(),{method:`HEAD`,headers:i,signal:t?.signal??this.#t.signal});if(!l.ok){if(l.status===404)return{exists:!1};await hs(l,this.url)}const o=l.headers.get(`content-type`)??void 0,u=l.headers.get(Tn)??void 0,d=l.headers.get(`etag`)??void 0,p=l.headers.get(`cache-control`)??void 0,g=l.headers.get(Ln)?.toLowerCase()===`true`;return o&&(this.contentType=o),{exists:!0,contentType:o,offset:u,etag:d,cacheControl:p,streamClosed:g}}async create(t){const{requestHeaders:i,fetchUrl:r}=await this.#f(),l=t?.contentType??this.#t.contentType;l&&(i[`content-type`]=l),t?.ttlSeconds!==void 0&&(i[mO]=String(t.ttlSeconds)),t?.expiresAt&&(i[SO]=t.expiresAt),t?.closed&&(i[Ln]=`true`);const o=qO(t?.body),u=await this.#e(r.toString(),{method:`PUT`,headers:i,body:o,signal:this.#t.signal});u.ok||await hs(u,this.url,{operation:`create`});const d=u.headers.get(`content-type`);return d?this.contentType=d:l&&(this.contentType=l),this}async delete(t){const{requestHeaders:i,fetchUrl:r}=await this.#f(),l=await this.#e(r.toString(),{method:`DELETE`,headers:i,signal:t?.signal??this.#t.signal});l.ok||await hs(l,this.url)}async close(t){const{requestHeaders:i,fetchUrl:r}=await this.#f(),l=t?.contentType??this.#t.contentType??this.contentType;l&&(i[`content-type`]=l),i[Ln]=`true`;let o;t?.body!==void 0&&(Xh(l)===`application/json`?o=`[${typeof t.body==`string`?t.body:new TextDecoder().decode(t.body)}]`:o=(typeof t.body==`string`,t.body));const u=await this.#e(r.toString(),{method:`POST`,headers:i,body:o,signal:t?.signal??this.#t.signal});if(u.status===409&&u.headers.get(Ln)?.toLowerCase()===`true`){const g=u.headers.get(Tn)??void 0;throw new mb(this.url,g)}return u.ok||await hs(u,this.url),{finalOffset:u.headers.get(Tn)??``}}async append(t,i){const r=HO(t)?await t:t;return this.#a&&this.#i?this.#p(r,i):this.#l(r,i)}async#l(t,i){const{requestHeaders:r,fetchUrl:l}=await this.#f(),o=i?.contentType??this.#t.contentType??this.contentType;o&&(r[`content-type`]=o),i?.seq&&(r[$h]=i.seq);const u=Xh(o)===`application/json`;let d;u?d=`[${typeof t==`string`?t:new TextDecoder().decode(t)}]`:typeof t==`string`?d=t:d=t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength);const p=await this.#e(l.toString(),{method:`POST`,headers:r,body:d,signal:i?.signal??this.#t.signal});p.ok||await hs(p,this.url)}async#p(t,i){return new Promise((r,l)=>{if(this.#c.push({data:t,seq:i?.seq,contentType:i?.contentType,signal:i?.signal,resolve:r,reject:l}),this.#i.idle()){const o=this.#c.splice(0);this.#i.push(o).catch(u=>{for(const d of o)d.reject(u)})}})}async#d(t){try{await this.#h(t);for(const i of t)i.resolve();if(this.#c.length>0){const i=this.#c.splice(0);this.#i.push(i).catch(r=>{for(const l of i)l.reject(r)})}}catch(i){for(const r of t)r.reject(i);for(const r of this.#c)r.reject(i);throw this.#c=[],i}}async#h(t){if(t.length===0)return;const{requestHeaders:i,fetchUrl:r}=await this.#f(),l=t[0]?.contentType??this.#t.contentType??this.contentType;l&&(i[`content-type`]=l);let o;for(let m=t.length-1;m>=0;m--)if(t[m].seq!==void 0){o=t[m].seq;break}o&&(i[$h]=o);const u=Xh(l)===`application/json`;let d;if(u)d=`[${t.map(v=>typeof v.data==`string`?v.data:new TextDecoder().decode(v.data)).join(`,`)}]`;else{const m=t.some(w=>w.data instanceof Uint8Array),v=t.some(w=>typeof w.data==`string`);if(m&&!v){const w=t.map(j=>j.data),b=w.reduce((j,O)=>j+O.length,0),E=new Uint8Array(b);let _=0;for(const j of w)E.set(j,_),_+=j.length;d=E}else if(v&&!m)d=t.map(w=>w.data).join(``);else{const w=new TextEncoder,b=t.map(O=>typeof O.data==`string`?w.encode(O.data):O.data),E=b.reduce((O,A)=>O+A.length,0),_=new Uint8Array(E);let j=0;for(const O of b)_.set(O,j),j+=O.length;d=_}}const p=[];this.#t.signal&&p.push(this.#t.signal);for(const m of t)m.signal&&p.push(m.signal);const g=p.length>0?AbortSignal.any(p):void 0,y=await this.#e(r.toString(),{method:`POST`,headers:i,body:d,signal:g});y.ok||await hs(y,this.url)}async appendStream(t,i){const{requestHeaders:r,fetchUrl:l}=await this.#f(),o=i?.contentType??this.#t.contentType??this.contentType;o&&(r[`content-type`]=o),i?.seq&&(r[$h]=i.seq);const u=KO(t),d=await this.#e(l.toString(),{method:`POST`,headers:r,body:u,duplex:`half`,signal:i?.signal??this.#t.signal});d.ok||await hs(d,this.url)}writable(t){const i=t?.producerId??`writable-${crypto.randomUUID().slice(0,8)}`;let r=null;const l=new wb(this,i,{autoClaim:!0,lingerMs:t?.lingerMs,maxBatchBytes:t?.maxBatchBytes,onError:o=>{r||(r=o),t?.onError?.(o)},signal:t?.signal??this.#t.signal});return new WritableStream({write(o){l.append(o)},async close(){if(await l.close(),r)throw r},abort(o){l.detach().catch(u=>{t?.onError?.(u)})}})}async stream(t){const i={...this.#t.headers,...t?.headers},r={...this.#t.params,...t?.params};return BO({url:this.url,headers:i,params:r,signal:t?.signal??this.#t.signal,fetch:this.#t.fetch,backoffOptions:this.#t.backoffOptions,offset:t?.offset,live:t?.live,json:t?.json,onError:t?.onError??this.#s,warnOnHttp:t?.warnOnHttp??this.#t.warnOnHttp})}async resolveHeaders(){return nl(this.#t.headers)}async#f(){const t=await nl(this.#t.headers),i=new URL(this.url),r=await fc(this.#t.params);for(const[l,o]of Object.entries(r))i.searchParams.set(l,o);return{requestHeaders:t,fetchUrl:i}}};function qO(n){if(n!==void 0)return typeof n==`string`?new TextEncoder().encode(n):n instanceof Uint8Array||n instanceof Blob||n instanceof FormData||n instanceof ReadableStream||n instanceof ArrayBuffer||ArrayBuffer.isView(n)?n:new TextEncoder().encode(JSON.stringify(n))}function KO(n){if(n instanceof ReadableStream)return n.pipeThrough(new TransformStream({transform(r,l){typeof r==`string`?l.enqueue(new TextEncoder().encode(r)):l.enqueue(r)}}));const t=new TextEncoder,i=n[Symbol.asyncIterator]();return new ReadableStream({async pull(r){try{const{done:l,value:o}=await i.next();l?r.close():typeof o==`string`?r.enqueue(t.encode(o)):r.enqueue(o)}catch(l){r.error(l)}},cancel(){i.return?.()}})}function VO(n){if(!n.url)throw new EO;if(n.signal&&!(n.signal instanceof AbortSignal))throw new CO;bb(n.url,n.warnOnHttp)}function Eb(n){return n!=null&&`operation`in n.headers}function Cb(n){return n!=null&&`control`in n.headers}var $O=class{handlers=new Map;pendingHandlers=new Set;isUpToDate=!1;preloadResolvers=[];preloadRejecters=[];seenTxids=new Set;pendingTxids=new Set;txidResolvers=new Map;existingKeys=new Map;registerHandler(n,t){this.handlers.set(n,t),this.existingKeys.has(n)||this.existingKeys.set(n,new Set)}dispatchChange(n){if(!Eb(n))return;n.headers.txid&&typeof n.headers.txid==`string`&&this.pendingTxids.add(n.headers.txid);const t=this.handlers.get(n.type);if(!t)return;let i=n.headers.operation;if(i!==`delete`&&(typeof n.value!=`object`||n.value===null))throw new Error(`StreamDB collections require object values; got ${typeof n.value} for type=${n.type}, key=${n.key}`);const l={...n.value??{}};l[t.primaryKey]=n.key,this.pendingHandlers.has(t)||(t.begin(),this.pendingHandlers.add(t)),i===`upsert`&&(i=this.existingKeys.get(n.type)?.has(n.key)?`update`:`insert`);const o=this.existingKeys.get(n.type);i===`insert`||i===`update`?o?.add(n.key):o?.delete(n.key);try{t.write(l,i)}catch(u){throw console.error(`[StreamDB] Error in handler.write():`,u),console.error(`[StreamDB] Event that caused error:`,{type:n.type,key:n.key,operation:i}),u}}dispatchControl(n){if(Cb(n))switch(n.headers.control){case`reset`:for(const t of this.handlers.values())t.truncate();for(const t of this.existingKeys.values())t.clear();this.pendingHandlers.clear(),this.isUpToDate=!1;break}}markUpToDate(){for(const n of this.pendingHandlers)try{n.commit()}catch(t){if(console.error(`[StreamDB] Error in handler.commit():`,t),t instanceof Error&&t.message.includes(`already exists in the collection`)&&t.message.includes(`live-query`)){console.warn(`[StreamDB] Known TanStack DB groupBy bug detected - continuing despite error`),console.warn(`[StreamDB] Queries with groupBy may show stale data until fixed`);continue}throw t}this.pendingHandlers.clear();for(const n of this.pendingTxids){this.seenTxids.add(n);const t=this.txidResolvers.get(n);if(t){for(const{resolve:i,timeoutId:r}of t)clearTimeout(r),i();this.txidResolvers.delete(n)}}if(this.pendingTxids.clear(),!this.isUpToDate){this.isUpToDate=!0;for(const n of this.handlers.values())n.markReady();for(const n of this.preloadResolvers)n();this.preloadResolvers=[]}}waitForUpToDate(){return this.isUpToDate?Promise.resolve():new Promise((n,t)=>{this.preloadResolvers.push(n),this.preloadRejecters.push(t)})}rejectAll(n){for(const t of this.preloadRejecters)t(n);this.preloadResolvers=[],this.preloadRejecters=[];for(const t of this.txidResolvers.values())for(const{reject:i,timeoutId:r}of t)clearTimeout(r),i(n);this.txidResolvers.clear()}get ready(){return this.isUpToDate}awaitTxId(n,t=5e3){return this.seenTxids.has(n)?Promise.resolve():new Promise((i,r)=>{const l=setTimeout(()=>{const o=this.txidResolvers.get(n);if(o){const u=o.findIndex(d=>d.timeoutId===l);u!==-1&&o.splice(u,1),o.length===0&&this.txidResolvers.delete(n)}r(new Error(`Timeout waiting for txid: ${n}`))},t);this.txidResolvers.has(n)||this.txidResolvers.set(n,[]),this.txidResolvers.get(n).push({resolve:i,reject:r,timeoutId:l})})}};function GO(n,t,i){return{sync:({begin:r,write:l,commit:o,markReady:u,truncate:d})=>(t.registerHandler(n,{begin:r,write:(p,g)=>{l({value:p,type:g})},commit:o,markReady:u,truncate:d,primaryKey:i}),t.ready&&u(),()=>{})}}const $S=new Set([`collections`,`preload`,`close`,`utils`,`actions`]);function YO(n,t,i){return{insert:({key:r,value:l,headers:o})=>{const u=i[`~standard`].validate(l);if(`issues`in u)throw new Error(`Validation failed for ${n} insert: ${u.issues?.map(g=>g.message).join(`, `)??`Unknown validation error`}`);const d=l[t],p=r??(d!=null&&d!==``?String(d):void 0);if(p==null||p===``)throw new Error(`Cannot create ${n} insert event: must provide either 'key' or a value with a non-empty '${t}' field`);return{type:n,key:p,value:l,headers:{...o,operation:`insert`}}},update:({key:r,value:l,oldValue:o,headers:u})=>{const d=i[`~standard`].validate(l);if(`issues`in d)throw new Error(`Validation failed for ${n} update: ${d.issues?.map(y=>y.message).join(`, `)??`Unknown validation error`}`);if(o!==void 0){const y=i[`~standard`].validate(o);if(`issues`in y)throw new Error(`Validation failed for ${n} update (oldValue): ${y.issues?.map(m=>m.message).join(`, `)??`Unknown validation error`}`)}const p=l[t],g=r??(p!=null&&p!==``?String(p):void 0);if(g==null||g===``)throw new Error(`Cannot create ${n} update event: must provide either 'key' or a value with a non-empty '${t}' field`);return{type:n,key:g,value:l,old_value:o,headers:{...u,operation:`update`}}},delete:({key:r,oldValue:l,headers:o})=>{if(l!==void 0){const d=i[`~standard`].validate(l);if(`issues`in d)throw new Error(`Validation failed for ${n} delete (oldValue): ${d.issues?.map(p=>p.message).join(`, `)??`Unknown validation error`}`)}const u=r??(l?String(l[t]):void 0);if(!u)throw new Error(`Cannot create ${n} delete event: must provide either 'key' or 'oldValue' with a ${t} field`);return{type:n,key:u,old_value:l,headers:{...o,operation:`delete`}}},upsert:({key:r,value:l,headers:o})=>{const u=i[`~standard`].validate(l);if(`issues`in u)throw new Error(`Validation failed for ${n} upsert: ${u.issues?.map(g=>g.message).join(`, `)??`Unknown validation error`}`);const d=l[t],p=r??(d!=null&&d!==``?String(d):void 0);if(p==null||p===``)throw new Error(`Cannot create ${n} upsert event: must provide either 'key' or a value with a non-empty '${t}' field`);return{type:n,key:p,value:l,headers:{...o,operation:`upsert`}}}}}function xb(n){for(const r of Object.keys(n))if($S.has(r))throw new Error(`Reserved collection name "${r}" - this would collide with StreamDB properties (${Array.from($S).join(`, `)})`);const t=new Map;for(const[r,l]of Object.entries(n)){const o=t.get(l.type);if(o)throw new Error(`Duplicate event type "${l.type}" - used by both "${o}" and "${r}" collections`);t.set(l.type,r)}const i={};for(const[r,l]of Object.entries(n))i[r]={...l,...YO(l.type,l.primaryKey,l.schema)};return i}function FO(n){const{streamOptions:t,state:i,actions:r}=n,l=new Ys(t),o=new $O,u={};for(const[w,b]of Object.entries(i)){const E=op({id:`stream-db:${w}`,schema:b.schema,getKey:_=>String(_[b.primaryKey]),sync:GO(b.type,o,b.primaryKey),startSync:!0,gcTime:0});console.log(`[StreamDB] Created collection "${w}":`,{type:typeof E,constructor:E.constructor.name,isCollection:E instanceof Object,hasSize:`size`in E}),u[w]=E}let d=null;const p=new AbortController;let g=!1;const y=async()=>{if(g)return;g=!0,d=await l.stream({live:!0,signal:p.signal});let w=0,b=Date.now();d.subscribeJson(_=>{try{w++,b=Date.now(),_.items.length>0&&console.log(`[StreamDB] Processing batch #${w}: ${_.items.length} items, upToDate=${_.upToDate}`);for(const j of _.items)Eb(j)?o.dispatchChange(j):Cb(j)&&o.dispatchControl(j);_.upToDate&&(console.log(`[StreamDB] Marking up-to-date after batch #${w}`),o.markUpToDate(),console.log(`[StreamDB] Successfully marked up-to-date`)),_.items.length>0&&console.log(`[StreamDB] Successfully processed batch #${w}`)}catch(j){console.error(`[StreamDB] Error processing batch:`,j),console.error(`[StreamDB] Failed batch:`,_),o.rejectAll(j),p.abort()}return Promise.resolve()});const E=setInterval(()=>{const _=Date.now()-b;console.log(`[StreamDB] Health: ${w} batches processed, last batch ${(_/1e3).toFixed(1)}s ago`)},15e3);p.signal.addEventListener(`abort`,()=>{clearInterval(E),console.log(`[StreamDB] Aborted - cleaning up health check`)})},m={stream:l,preload:async()=>{await y(),await o.waitForUpToDate()},close:()=>{o.rejectAll(new Error(`StreamDB closed`)),p.abort()},utils:{awaitTxId:(w,b)=>o.awaitTxId(w,b)}};console.log(`[StreamDB] Creating db object with collections:`,Object.keys(u));const v={collections:u,...m};if(console.log(`[StreamDB] db.collections:`,Object.keys(v.collections)),console.log(`[StreamDB] db.collections.events:`,v.collections.events),r){const w=r({db:v,stream:l}),b={};for(const[E,_]of Object.entries(w))b[E]=uA({onMutate:_.onMutate,mutationFn:_.mutationFn});return{...v,actions:b}}return v}const bp=600,QO=bp/2*1e3,XO=3600*24,JO={"~standard":{version:1,vendor:`durable-streams`,validate:n=>{const t=n;return typeof t.roomId!=`string`||t.roomId.length===0?{issues:[{message:`roomId must be a non-empty string`}]}:typeof t.name!=`string`||t.name.length===0?{issues:[{message:`name must be a non-empty string`}]}:typeof t.boardSize!=`string`?{issues:[{message:`boardSize must be a string`}]}:typeof t.createdAt!=`number`?{issues:[{message:`createdAt must be a number`}]}:typeof t.expiresAt!=`number`?{issues:[{message:`expiresAt must be a number`}]}:t.playerCount!==void 0&&typeof t.playerCount!=`number`?{issues:[{message:`playerCount must be a number`}]}:{value:t}}}},Jh=xb({rooms:{schema:JO,type:`stream`,primaryKey:`roomId`}}),ZO={"~standard":{version:1,vendor:`durable-streams`,validate:n=>{const t=n;return typeof t.playerName!=`string`||t.playerName.length===0?{issues:[{message:`playerName must be a non-empty string`}]}:typeof t.score!=`number`?{issues:[{message:`score must be a number`}]}:typeof t.timestamp!=`number`?{issues:[{message:`timestamp must be a number`}]}:{value:t}}}},GS=xb({scores:{schema:ZO,type:`stream`,primaryKey:`playerName`}});function _b(n){const[t,i]=J.useState({db:null,isLoading:!0,error:null}),r=n.streamOptions.url;return J.useEffect(()=>{let l=null;const o=new AbortController,u=()=>o.signal.aborted;return(async()=>{i({db:null,isLoading:!0,error:null});try{const g=await new Ys({url:r,headers:n.streamOptions.headers,contentType:`application/json`}).head();if(u()||(g.exists||await Ys.create({url:r,headers:n.streamOptions.headers,contentType:`application/json`,ttlSeconds:n.ttlSeconds}),l=await FO(n),await l.preload(),u()))return;i({db:l,isLoading:!1,error:null})}catch(p){if(u())return;const g=p instanceof Error?p:new Error(String(p));console.error(`[useStreamDB] Failed to initialize ${r}:`,g),i({db:null,isLoading:!1,error:g})}})(),()=>{o.abort(),l&&l.close()}},[r]),t}function WO(n,t){return{streamOptions:{url:n,headers:t,contentType:`application/json`},state:Jh,ttlSeconds:XO,actions:({db:i,stream:r})=>({addRoom:{onMutate:l=>{i.collections.rooms.insert(l)},mutationFn:async l=>{const o=crypto.randomUUID();await r.append(JSON.stringify(Jh.rooms.insert({value:l,headers:{txid:o}}))),await i.utils.awaitTxId(o)}},deleteRoom:{onMutate:l=>{i.collections.rooms.delete(l)},mutationFn:async l=>{const o=crypto.randomUUID();await r.append(JSON.stringify(Jh.rooms.delete({key:l,headers:{txid:o}}))),await i.utils.awaitTxId(o)}}})}}function PO(n,t){return _b(WO(n,t))}const Tb=J.createContext(null);function Ab(){const n=J.useContext(Tb);if(!n)throw new Error(`useRegistryContext must be used within RegistryProvider`);return n}function tR({children:n}){const{dsEndpoint:t,dsHeaders:i}=Zd(),{db:r,isLoading:l,error:o}=PO(`${t}/__snake_rooms`,i);return l?F.jsxs(`div`,{style:YS.center,children:[F.jsx(`style`,{children:`@import url('https://fonts.googleapis.com/css2?family=Press+Start+2P&display=swap');`}),F.jsx(`div`,{style:{color:`#d0bcff`,fontSize:8},children:`LOADING...`})]}):o||!r?F.jsxs(`div`,{style:YS.center,children:[F.jsx(`style`,{children:`@import url('https://fonts.googleapis.com/css2?family=Press+Start+2P&display=swap');`}),F.jsxs(`div`,{style:{color:`#FF3D71`,fontSize:8},children:[`Registry Error: `,o?.message||`Failed to load`]})]}):F.jsx(Tb.Provider,{value:{registryDB:r},children:n})}const YS={center:{display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,height:`100vh`,gap:16,fontFamily:`'Press Start 2P', monospace`,background:`#1b1b1f`}},Zh=1;function eR(n,t=[]){const i=n&&typeof n==`object`&&typeof n.subscribeChanges==`function`&&typeof n.startSyncImmediate==`function`&&typeof n.id==`string`,r=J.useRef(null),l=J.useRef(null),o=J.useRef(null),u=J.useRef(0),d=J.useRef(null),p=!r.current||i&&o.current!==n||!i&&(l.current===null||l.current.length!==t.length||l.current.some((b,E)=>b!==t[E]));if(p)if(i)n.config?.syncMode===`on-demand`&&console.warn(`[useLiveQuery] Warning: Passing a collection with syncMode "on-demand" directly to useLiveQuery will not load any data. In on-demand mode, data is only loaded when queries with predicates request it. + +Instead, use a query builder function: + const { data } = useLiveQuery((q) => q.from({ c: myCollection }).select(({ c }) => c)) + +Or switch to syncMode "eager" if you want all data to sync automatically.`),n.startSyncImmediate(),r.current=n,o.current=n;else if(typeof n==`function`){const b=new Zt,E=n(b);if(E==null)r.current=null;else if(E instanceof cp)E.startSyncImmediate(),r.current=E;else if(E instanceof Zt)r.current=Kh({query:n,startSync:!0,gcTime:Zh});else if(E&&typeof E==`object`)r.current=Kh({startSync:!0,gcTime:Zh,...E});else throw new Error(`useLiveQuery callback must return a QueryBuilder, LiveQueryCollectionConfig, Collection, undefined, or null. Got: ${typeof E}`);l.current=[...t]}else r.current=Kh({startSync:!0,gcTime:Zh,...n}),l.current=[...t];p&&(u.current=0,d.current=null);const g=J.useRef(null);(!g.current||p)&&(g.current=b=>{if(!r.current)return()=>{};const E=r.current.subscribeChanges(()=>{u.current+=1,b()});return r.current.status===`ready`&&(u.current+=1,b()),()=>{E.unsubscribe()}});const y=J.useRef(null);(!y.current||p)&&(y.current=()=>{const b=u.current,E=r.current;return(!d.current||d.current.version!==b||d.current.collection!==E)&&(d.current={collection:E,version:b}),d.current});const m=J.useSyncExternalStore(g.current,y.current),v=J.useRef(null),w=J.useRef(null);if(!v.current||v.current.version!==m.version||v.current.collection!==m.collection){if(!m.collection)w.current={state:void 0,data:void 0,collection:void 0,status:`disabled`,isLoading:!1,isReady:!0,isIdle:!1,isError:!1,isCleanedUp:!1,isEnabled:!1};else{const b=Array.from(m.collection.entries()),_=m.collection.config.singleResult;let j=null,O=null;w.current={get state(){return j||(j=new Map(b)),j},get data(){return O||(O=b.map(([,A])=>A)),_?O[0]:O},collection:m.collection,status:m.collection.status,isLoading:m.collection.status===`loading`,isReady:m.collection.status===`ready`,isIdle:m.collection.status===`idle`,isError:m.collection.status===`error`,isCleanedUp:m.collection.status===`cleaned-up`,isEnabled:!0}}v.current=m}return w.current}const Nt={bg:`#1b1b1f`,card:`#161618`,border:`#2e2e32`,text:`rgba(235,235,245,0.68)`,accent:`#d0bcff`,dim:`rgba(235,235,245,0.38)`},tc=[{label:`32x32`,cols:32,rows:32},{label:`64x64`,cols:64,rows:64},{label:`128x128`,cols:128,rows:128}];function Wh(n,t){return`${n}__${t.cols}x${t.rows}`}function nR(){const n=[`neon`,`cyber`,`pixel`,`hyper`,`turbo`,`mega`,`ultra`,`nova`],t=n[Math.floor(Math.random()*n.length)],i=Math.floor(Math.random()*900)+100;return`${t}-${i}`}function sR({playerName:n,onPlayerNameChange:t,onJoinRoom:i}){const{registryDB:r}=Ab(),[l,o]=J.useState(nR),[u,d]=J.useState(1),[p,g]=J.useState(!1),[y,m]=J.useState(0),[v,w]=J.useState(``),[,b]=J.useState(0);J.useEffect(()=>{const O=setInterval(()=>b(A=>A+1),1e3);return()=>clearInterval(O)},[]);const E=Date.now(),{data:_=[]}=eR(O=>O.from({rooms:r.collections.rooms}).where(({rooms:A})=>wd(A.expiresAt,E)).orderBy(({rooms:A})=>A.createdAt,`desc`)),j=async()=>{if(!p){g(!0);try{const O=l.trim()||`room-${Math.random().toString(36).slice(2,7)}`,A=tc[u],M=Wh(O,A),G=Date.now(),q={roomId:M,name:O,boardSize:`${A.cols}x${A.rows}`,createdAt:G,expiresAt:G+bp*1e3};await r.actions.addRoom(q),o(``),i(M)}catch(O){console.error(`Failed to create room:`,O)}finally{g(!1)}}};return F.jsxs(`div`,{style:mn.container,children:[F.jsx(`style`,{children:` + @import url('https://fonts.googleapis.com/css2?family=Press+Start+2P&display=swap'); + .lobby-btn:active { opacity: 0.7; } + `}),F.jsx(`div`,{style:mn.title,children:`TERRITORY WARS`}),F.jsx(`div`,{style:{fontSize:7,color:Nt.dim,marginBottom:20,textAlign:`center`,maxWidth:340,lineHeight:1.6},children:`Claim 30% territory or lead when time runs out.`}),F.jsxs(`div`,{style:mn.card,children:[F.jsx(`div`,{style:mn.cardTitle,children:`NAME`}),F.jsx(`input`,{style:mn.input,value:n,onChange:O=>t(O.target.value),placeholder:`Enter your name...`,maxLength:20})]}),F.jsxs(`div`,{style:mn.card,children:[F.jsx(`div`,{style:mn.cardTitle,children:`ROOM`}),F.jsx(`input`,{style:mn.input,value:l,onChange:O=>o(O.target.value),placeholder:`room name`,onKeyDown:O=>O.key===`Enter`&&j()}),F.jsx(`div`,{style:mn.cardTitle,children:`BOARD SIZE`}),F.jsx(`div`,{style:{display:`flex`,gap:6,marginBottom:10},children:tc.map((O,A)=>F.jsx(`button`,{className:`lobby-btn`,style:{flex:1,padding:`6px 0`,fontSize:7,fontFamily:`inherit`,background:A===u?Nt.accent:`transparent`,color:A===u?`#000`:Nt.accent,border:`1px solid ${Nt.accent}`,cursor:`pointer`,letterSpacing:1},onClick:()=>d(A),children:O.label},O.label))}),F.jsx(`button`,{className:`lobby-btn`,style:{...mn.createBtn,opacity:p?.6:1},onClick:j,disabled:p,children:p?`STARTING...`:`START`})]}),F.jsxs(`div`,{style:mn.card,children:[F.jsx(`div`,{style:mn.cardTitle,children:`ROOMS`}),F.jsxs(`div`,{style:{display:`flex`,flexDirection:`column`,gap:6},children:[_.slice(y*3,y*3+3).map(O=>F.jsx(iR,{room:O,onJoin:()=>i(O.roomId)},O.roomId)),F.jsxs(`div`,{style:{display:`flex`,alignItems:`center`,justifyContent:`space-between`,background:Nt.bg,border:`1px solid ${Nt.border}`,padding:`8px 12px`},children:[F.jsx(`input`,{style:{fontSize:8,color:Nt.text,fontFamily:`inherit`,background:`transparent`,border:`none`,outline:`none`,flex:1,padding:0},value:v,onChange:O=>w(O.target.value),placeholder:`room-id`,onKeyDown:O=>{if(O.key===`Enter`&&v.trim()){const A=_.find(M=>M.name===v.trim());i(A?A.roomId:Wh(v.trim(),tc[u]))}}}),v.trim()&&F.jsx(`button`,{className:`lobby-btn`,style:{background:Nt.accent,color:`#000`,border:`none`,fontFamily:`inherit`,fontSize:7,padding:`4px 12px`,cursor:`pointer`,letterSpacing:1,flexShrink:0},onClick:()=>{const O=_.find(A=>A.name===v.trim());i(O?O.roomId:Wh(v.trim(),tc[u]))},children:`JOIN`})]})]}),_.length>3&&F.jsxs(`div`,{style:{display:`flex`,justifyContent:`center`,gap:8,marginTop:10},children:[F.jsx(`button`,{className:`lobby-btn`,style:{fontFamily:`inherit`,fontSize:6,background:Nt.bg,color:Nt.dim,border:`1px solid ${Nt.border}`,cursor:`pointer`,width:28,padding:`4px 0`,opacity:y===0?.3:1},disabled:y===0,onClick:()=>m(O=>O-1),children:`<`}),F.jsxs(`span`,{style:{fontSize:7,color:Nt.dim,lineHeight:`24px`},children:[y+1,`/`,Math.ceil(_.length/3)]}),F.jsx(`button`,{className:`lobby-btn`,style:{fontFamily:`inherit`,fontSize:6,background:Nt.bg,color:Nt.dim,border:`1px solid ${Nt.border}`,cursor:`pointer`,width:28,padding:`4px 0`,opacity:y>=Math.ceil(_.length/3)-1?.3:1},disabled:y>=Math.ceil(_.length/3)-1,onClick:()=>m(O=>O+1),children:`>`})]})]})]})}function iR({room:n,onJoin:t}){const[i,r]=J.useState(!1),l=o=>{o.stopPropagation(),navigator.clipboard.writeText(n.name).catch(()=>{}),r(!0),setTimeout(()=>r(!1),1200)};return F.jsxs(`div`,{style:{display:`flex`,alignItems:`center`,justifyContent:`space-between`,background:Nt.bg,border:`1px solid ${Nt.border}`,padding:`8px 12px`,cursor:`pointer`},onClick:t,children:[F.jsx(`div`,{style:{display:`flex`,alignItems:`center`,gap:6},onClick:l,title:`Click to copy room name`,children:F.jsx(`span`,{style:{fontSize:8,color:i?Nt.accent:Nt.text,cursor:`pointer`},children:i?`COPIED`:n.name})}),F.jsx(`button`,{className:`lobby-btn`,style:{background:Nt.accent,color:`#000`,border:`none`,fontFamily:`inherit`,fontSize:7,padding:`4px 12px`,cursor:`pointer`,letterSpacing:1},onClick:o=>{o.stopPropagation(),t()},children:`JOIN`})]})}const mn={container:{display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,minHeight:`100vh`,fontFamily:`'Press Start 2P', monospace`,background:Nt.bg,color:Nt.text,padding:20},title:{fontSize:16,letterSpacing:4,color:Nt.accent,marginBottom:6},card:{background:Nt.card,border:`1px solid ${Nt.border}`,padding:16,width:`100%`,maxWidth:340,marginBottom:12},cardTitle:{fontSize:7,color:Nt.accent,letterSpacing:2,marginBottom:10},input:{width:`100%`,background:Nt.bg,border:`1px solid ${Nt.border}`,padding:`8px 10px`,color:Nt.text,fontFamily:`inherit`,fontSize:8,marginBottom:10,outline:`none`,boxSizing:`border-box`},createBtn:{width:`100%`,padding:`10px 0`,fontSize:8,fontFamily:`inherit`,background:Nt.accent,color:`#000`,border:`none`,cursor:`pointer`,letterSpacing:2}},An=()=>new Map,Ld=n=>{const t=An();return n.forEach((i,r)=>{t.set(r,i)}),t},Ws=(n,t,i)=>{let r=n.get(t);return r===void 0&&n.set(t,r=i()),r},rR=(n,t)=>{const i=[];for(const[r,l]of n)i.push(t(l,r));return i},aR=(n,t)=>{for(const[i,r]of n)if(t(r,i))return!0;return!1},Hr=()=>new Set,Ph=n=>n[n.length-1],lR=(n,t)=>{for(let i=0;i{for(let i=0;i{for(let i=0;i{const i=new Array(n);for(let r=0;r{this.off(t,r),i(...l)};this.on(t,r)}off(t,i){const r=this._observers.get(t);r!==void 0&&(r.delete(i),r.size===0&&this._observers.delete(t))}emit(t,i){return Ei((this._observers.get(t)||An()).values()).forEach(r=>r(...i))}destroy(){this._observers=An()}};const Hn=Math.floor,hc=Math.abs,Rb=(n,t)=>nn>t?n:t,Db=n=>n!==0?n<0:1/n<0,FS=1,QS=2,td=4,ed=8,hl=32,gs=64,rn=128,Qc=31,Id=63,wi=127,uR=2147483647,Oc=Number.MAX_SAFE_INTEGER,XS=Number.MIN_SAFE_INTEGER,fR=Number.isInteger||(n=>typeof n==`number`&&isFinite(n)&&Hn(n)===n),hR=String.fromCharCode,dR=n=>n.toLowerCase(),pR=/^\s*/g,gR=n=>n.replace(pR,``),yR=/([A-Z])/g,JS=(n,t)=>gR(n.replace(yR,i=>`${t}${dR(i)}`)),mR=n=>{const t=unescape(encodeURIComponent(n)),i=t.length,r=new Uint8Array(i);for(let l=0;ldl.encode(n),vR=dl?SR:mR;let sl=typeof TextDecoder>`u`?null:new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0});sl&&sl.decode(new Uint8Array).length===1&&(sl=null);const bR=(n,t)=>oR(t,()=>n).join(``);let Tl=class{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}};const Xc=()=>new Tl,wR=n=>{let t=n.cpos;for(let i=0;i{const t=new Uint8Array(wR(n));let i=0;for(let r=0;r{const i=n.cbuf.length;i-n.cpos{const i=n.cbuf.length;n.cpos===i&&(n.bufs.push(n.cbuf),n.cbuf=new Uint8Array(i*2),n.cpos=0),n.cbuf[n.cpos++]=t},Hd=ye,Dt=(n,t)=>{for(;t>wi;)ye(n,rn|wi&t),t=Hn(t/128);ye(n,wi&t)},Ep=(n,t)=>{const i=Db(t);for(i&&(t=-t),ye(n,(t>Id?rn:0)|(i?gs:0)|Id&t),t=Hn(t/64);t>0;)ye(n,(t>wi?rn:0)|wi&t),t=Hn(t/128)},qd=new Uint8Array(3e4),CR=qd.length/3,xR=(n,t)=>{if(t.length{const i=unescape(encodeURIComponent(t)),r=i.length;Dt(n,r);for(let l=0;l{const i=n.cbuf.length,r=n.cpos,l=Rb(i-r,t.length),o=t.length-l;n.cbuf.set(t.subarray(0,l),r),n.cpos+=l,o>0&&(n.bufs.push(n.cbuf),n.cbuf=new Uint8Array(Yr(i*2,o)),n.cbuf.set(t.subarray(l)),n.cpos=o)},nn=(n,t)=>{Dt(n,t.byteLength),Jc(n,t)},Cp=(n,t)=>{ER(n,t);const i=new DataView(n.cbuf.buffer,n.cpos,t);return n.cpos+=t,i},TR=(n,t)=>Cp(n,4).setFloat32(0,t,!1),AR=(n,t)=>Cp(n,8).setFloat64(0,t,!1),OR=(n,t)=>Cp(n,8).setBigInt64(0,t,!1),ZS=new DataView(new ArrayBuffer(4)),RR=n=>(ZS.setFloat32(0,n),ZS.getFloat32(0)===n),pl=(n,t)=>{switch(typeof t){case`string`:ye(n,119),Rr(n,t);break;case`number`:fR(t)&&hc(t)<=uR?(ye(n,125),Ep(n,t)):RR(t)?(ye(n,124),TR(n,t)):(ye(n,123),AR(n,t));break;case`bigint`:ye(n,122),OR(n,t);break;case`object`:if(t===null)ye(n,126);else if(Fc(t)){ye(n,117),Dt(n,t.length);for(let i=0;i0&&Dt(this,this.count-1),this.count=1,this.w(this,t),this.s=t)}}const PS=n=>{n.count>0&&(Ep(n.encoder,n.count===1?n.s:-n.s),n.count>1&&Dt(n.encoder,n.count-2))};class dc{constructor(){this.encoder=new Tl,this.s=0,this.count=0}write(t){this.s===t?this.count++:(PS(this),this.count=1,this.s=t)}toUint8Array(){return PS(this),In(this.encoder)}}const tv=n=>{if(n.count>0){const t=n.diff*2+(n.count===1?0:1);Ep(n.encoder,t),n.count>1&&Dt(n.encoder,n.count-2)}};class nd{constructor(){this.encoder=new Tl,this.s=0,this.count=0,this.diff=0}write(t){this.diff===t-this.s?(this.s=t,this.count++):(tv(this),this.count=1,this.diff=t-this.s,this.s=t)}toUint8Array(){return tv(this),In(this.encoder)}}class DR{constructor(){this.sarr=[],this.s=``,this.lensE=new dc}write(t){this.s+=t,this.s.length>19&&(this.sarr.push(this.s),this.s=``),this.lensE.write(t.length)}toUint8Array(){const t=new Tl;return this.sarr.push(this.s),this.s=``,Rr(t,this.sarr.join(``)),Jc(t,this.lensE.toUint8Array()),In(t)}}const qn=n=>new Error(n),On=()=>{throw qn(`Method unimplemented`)},bn=()=>{throw qn(`Unexpected case`)},Mb=qn(`Unexpected end of array`),kb=qn(`Integer out of Range`);let Zc=class{constructor(t){this.arr=t,this.pos=0}};const xp=n=>new Zc(n),MR=n=>n.pos!==n.arr.length,kR=(n,t)=>{const i=new Uint8Array(n.arr.buffer,n.pos+n.arr.byteOffset,t);return n.pos+=t,i},sn=n=>kR(n,Ot(n)),qr=n=>n.arr[n.pos++],Ot=n=>{let t=0,i=1;const r=n.arr.length;for(;n.posOc)throw kb}throw Mb},_p=n=>{let t=n.arr[n.pos++],i=t&Id,r=64;const l=(t&gs)>0?-1:1;if((t&rn)===0)return l*i;const o=n.arr.length;for(;n.posOc)throw kb}throw Mb},UR=n=>{let t=Ot(n);if(t===0)return``;{let i=String.fromCodePoint(qr(n));if(--t<100)for(;t--;)i+=String.fromCodePoint(qr(n));else for(;t>0;){const r=t<1e4?t:1e4,l=n.arr.subarray(n.pos,n.pos+r);n.pos+=r,i+=String.fromCodePoint.apply(null,l),t-=r}return decodeURIComponent(escape(i))}},zR=n=>sl.decode(sn(n)),Dr=sl?zR:UR,Tp=(n,t)=>{const i=new DataView(n.arr.buffer,n.arr.byteOffset+n.pos,t);return n.pos+=t,i},NR=n=>Tp(n,4).getFloat32(0,!1),jR=n=>Tp(n,8).getFloat64(0,!1),BR=n=>Tp(n,8).getBigInt64(0,!1),LR=[n=>{},n=>null,_p,NR,jR,BR,n=>!1,n=>!0,Dr,n=>{const t=Ot(n),i={};for(let r=0;r{const t=Ot(n),i=[];for(let r=0;rLR[127-qr(n)](n);class ev extends Zc{constructor(t,i){super(t),this.reader=i,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),MR(this)?this.count=Ot(this)+1:this.count=-1),this.count--,this.s}}class pc extends Zc{constructor(t){super(t),this.s=0,this.count=0}read(){if(this.count===0){this.s=_p(this);const t=Db(this.s);this.count=1,t&&(this.s=-this.s,this.count=Ot(this)+2)}return this.count--,this.s}}class sd extends Zc{constructor(t){super(t),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const t=_p(this),i=t&1;this.diff=Hn(t/2),this.count=1,i&&(this.count=Ot(this)+2)}return this.s+=this.diff,this.count--,this.s}}class IR{constructor(t){this.decoder=new pc(t),this.str=Dr(this.decoder),this.spos=0}read(){const t=this.spos+this.decoder.read(),i=this.str.slice(this.spos,t);return this.spos=t,i}}const HR=crypto.getRandomValues.bind(crypto),Ub=()=>HR(new Uint32Array(1))[0],qR=`10000000-1000-4000-8000`+-1e11,KR=()=>qR.replace(/[018]/g,n=>(n^Ub()&15>>n/4).toString(16)),nv=n=>new Promise(n);Promise.all.bind(Promise);const sv=n=>n===void 0?null:n;class VR{constructor(){this.map=new Map}setItem(t,i){this.map.set(t,i)}getItem(t){return this.map.get(t)}}let zb=new VR,$R=!0;try{typeof localStorage<`u`&&localStorage&&(zb=localStorage,$R=!1)}catch{}const GR=zb,yl=Symbol(`Equality`),Nb=(n,t)=>n===t||!!n?.[yl]?.(t)||!1,YR=n=>typeof n==`object`,FR=Object.assign,QR=Object.keys,XR=(n,t)=>{for(const i in n)t(n[i],i)},Rc=n=>QR(n).length,JR=n=>{for(const t in n)return!1;return!0},Al=(n,t)=>{for(const i in n)if(!t(n[i],i))return!1;return!0},Ap=(n,t)=>Object.prototype.hasOwnProperty.call(n,t),ZR=(n,t)=>n===t||Rc(n)===Rc(t)&&Al(n,(i,r)=>(i!==void 0||Ap(t,r))&&Nb(t[r],i)),WR=Object.freeze,jb=n=>{for(const t in n){const i=n[t];(typeof i==`object`||typeof i==`function`)&&jb(n[t])}return WR(n)},Op=(n,t,i=0)=>{try{for(;i{if(n===t)return!0;if(n==null||t==null||n.constructor!==t.constructor&&(n.constructor||Object)!==(t.constructor||Object))return!1;if(n[yl]!=null)return n[yl](t);switch(n.constructor){case ArrayBuffer:n=new Uint8Array(n),t=new Uint8Array(t);case Uint8Array:{if(n.byteLength!==t.byteLength)return!1;for(let i=0;it.includes(n);var Bb={};const ml=typeof process<`u`&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<`u`?process:0)===`[object process]`;let Nn;const tD=()=>{if(Nn===void 0)if(ml){Nn=An();const n=process.argv;let t=null;for(let i=0;i{if(n.length!==0){const[t,i]=n.split(`=`);Nn.set(`--${JS(t,`-`)}`,i),Nn.set(`-${JS(t,`-`)}`,i)}})):Nn=An();return Nn},Kd=n=>tD().has(n),Dc=n=>sv(ml?Bb[n.toUpperCase().replaceAll(`-`,`_`)]:GR.getItem(n)),Lb=n=>Kd(`--`+n)||Dc(n)!==null,eD=Lb(`production`),nD=ml&&PR(Bb.FORCE_COLOR,[`true`,`1`,`2`]),sD=nD||!Kd(`--no-colors`)&&!Lb(`no-color`)&&(!ml||process.stdout.isTTY)&&(!ml||Kd(`--color`)||Dc(`COLORTERM`)!==null||(Dc(`TERM`)||``).includes(`color`)),iD=n=>new Uint8Array(n),rD=n=>{const t=iD(n.byteLength);return t.set(n),t};class aD{constructor(t,i){this.left=t,this.right=i}}const us=(n,t)=>new aD(n,t),iv=n=>n.next()>=.5,id=(n,t,i)=>Hn(n.next()*(i+1-t)+t),Ib=(n,t,i)=>Hn(n.next()*(i+1-t)+t),Rp=(n,t,i)=>Ib(n,t,i),lD=n=>hR(Rp(n,97,122)),oD=(n,t=0,i=20)=>{const r=Rp(n,t,i);let l=``;for(let o=0;ot[Rp(n,0,t.length-1)],cD=Symbol(`0schema`);class uD{constructor(){this._rerrs=[]}extend(t,i,r,l=null){this._rerrs.push({path:t,expected:i,has:r,message:l})}toString(){const t=[];for(let i=this._rerrs.length-1;i>0;i--){const r=this._rerrs[i];t.push(bR(` `,(this._rerrs.length-i)*2)+`${r.path!=null?`[${r.path}] `:``}${r.has} doesn't match ${r.expected}. ${r.message}`)}return t.join(` +`)}}const Vd=(n,t)=>n===t?!0:n==null||t==null||n.constructor!==t.constructor?!1:n[yl]?Nb(n,t):Fc(n)?wp(n,i=>Ob(t,r=>Vd(i,r))):YR(n)?Al(n,(i,r)=>Vd(i,t[r])):!1;class Ne{static _dilutes=!1;extends(t){let[i,r]=[this.shape,t.shape];return this.constructor._dilutes&&([r,i]=[i,r]),Vd(i,r)}equals(t){return this.constructor===t.constructor&&gc(this.shape,t.shape)}[cD](){return!0}[yl](t){return this.equals(t)}validate(t){return this.check(t)}check(t,i){On()}get nullable(){return Fr(this,nu)}get optional(){return new Kb(this)}cast(t){return rv(t,this),t}expect(t){return rv(t,this),t}}class Dp extends Ne{constructor(t,i){super(),this.shape=t,this._c=i}check(t,i=void 0){const r=t?.constructor===this.shape&&(this._c==null||this._c(t));return!r&&i?.extend(null,this.shape.name,t?.constructor.name,t?.constructor!==this.shape?`Constructor match failed`:`Check failed`),r}}const oe=(n,t=null)=>new Dp(n,t);oe(Dp);class Mp extends Ne{constructor(t){super(),this.shape=t}check(t,i){const r=this.shape(t);return!r&&i?.extend(null,`custom prop`,t?.constructor.name,`failed to check custom prop`),r}}const ve=n=>new Mp(n);oe(Mp);class Wc extends Ne{constructor(t){super(),this.shape=t}check(t,i){const r=this.shape.some(l=>l===t);return!r&&i?.extend(null,this.shape.join(` | `),t.toString()),r}}const Pc=(...n)=>new Wc(n),Hb=oe(Wc),fD=RegExp.escape||(n=>n.replace(/[().|&,$^[\]]/g,t=>`\\`+t)),qb=n=>{if(Kr.check(n))return[fD(n)];if(Hb.check(n))return n.shape.map(t=>t+``);if(Zb.check(n))return[`[+-]?\\d+.?\\d*`];if(Wb.check(n))return[`.*`];if(Mc.check(n))return n.shape.map(qb).flat(1);bn()};class hD extends Ne{constructor(t){super(),this.shape=t,this._r=new RegExp(`^`+t.map(qb).map(i=>`(${i.join(`|`)})`).join(``)+`$`)}check(t,i){const r=this._r.exec(t)!=null;return!r&&i?.extend(null,this._r.toString(),t.toString(),`String doesn't match string template.`),r}}oe(hD);const dD=Symbol(`optional`);class Kb extends Ne{constructor(t){super(),this.shape=t}check(t,i){const r=t===void 0||this.shape.check(t);return!r&&i?.extend(null,`undefined (optional)`,`()`),r}get[dD](){return!0}}const pD=oe(Kb);class gD extends Ne{check(t,i){return i?.extend(null,`never`,typeof t),!1}}oe(gD);class tu extends Ne{constructor(t,i=!1){super(),this.shape=t,this._isPartial=i}static _dilutes=!0;get partial(){return new tu(this.shape,!0)}check(t,i){return t==null?(i?.extend(null,`object`,`null`),!1):Al(this.shape,(r,l)=>{const o=this._isPartial&&!Ap(t,l)||r.check(t[l],i);return!o&&i?.extend(l.toString(),r.toString(),typeof t[l],`Object property does not match`),o})}}const yD=n=>new tu(n),mD=oe(tu),SD=ve(n=>n!=null&&(n.constructor===Object||n.constructor==null));class Vb extends Ne{constructor(t,i){super(),this.shape={keys:t,values:i}}check(t,i){return t!=null&&Al(t,(r,l)=>{const o=this.shape.keys.check(l,i);return!o&&i?.extend(l+``,`Record`,typeof t,o?`Key doesn't match schema`:`Value doesn't match value`),o&&this.shape.values.check(r,i)})}}const $b=(n,t)=>new Vb(n,t),vD=oe(Vb);class Gb extends Ne{constructor(t){super(),this.shape=t}check(t,i){return t!=null&&Al(this.shape,(r,l)=>{const o=r.check(t[l],i);return!o&&i?.extend(l.toString(),`Tuple`,typeof r),o})}}const bD=(...n)=>new Gb(n);oe(Gb);class Yb extends Ne{constructor(t){super(),this.shape=t.length===1?t[0]:new kp(t)}check(t,i){const r=Fc(t)&&wp(t,l=>this.shape.check(l));return!r&&i?.extend(null,`Array`,``),r}}const Fb=(...n)=>new Yb(n),wD=oe(Yb),ED=ve(n=>Fc(n));class Qb extends Ne{constructor(t,i){super(),this.shape=t,this._c=i}check(t,i){const r=t instanceof this.shape&&(this._c==null||this._c(t));return!r&&i?.extend(null,this.shape.name,t?.constructor.name),r}}const CD=(n,t=null)=>new Qb(n,t);oe(Qb);const xD=CD(Ne);class _D extends Ne{constructor(t){super(),this.len=t.length-1,this.args=bD(...t.slice(-1)),this.res=t[this.len]}check(t,i){const r=t.constructor===Function&&t.length<=this.len;return!r&&i?.extend(null,`function`,typeof t),r}}const TD=oe(_D),AD=ve(n=>typeof n==`function`);class OD extends Ne{constructor(t){super(),this.shape=t}check(t,i){const r=wp(this.shape,l=>l.check(t,i));return!r&&i?.extend(null,`Intersectinon`,typeof t),r}}oe(OD,n=>n.shape.length>0);class kp extends Ne{static _dilutes=!0;constructor(t){super(),this.shape=t}check(t,i){const r=Ob(this.shape,l=>l.check(t,i));return i?.extend(null,`Union`,typeof t),r}}const Fr=(...n)=>n.findIndex(t=>Mc.check(t))>=0?Fr(...n.map(t=>Sl(t)).map(t=>Mc.check(t)?t.shape:[t]).flat(1)):n.length===1?n[0]:new kp(n),Mc=oe(kp),Xb=()=>!0,kc=ve(Xb),RD=oe(Mp,n=>n.shape===Xb),Up=ve(n=>typeof n==`bigint`),DD=ve(n=>n===Up),Jb=ve(n=>typeof n==`symbol`);ve(n=>n===Jb);const Mr=ve(n=>typeof n==`number`),Zb=ve(n=>n===Mr),Kr=ve(n=>typeof n==`string`),Wb=ve(n=>n===Kr),eu=ve(n=>typeof n==`boolean`),MD=ve(n=>n===eu),Pb=Pc(void 0);oe(Wc,n=>n.shape.length===1&&n.shape[0]===void 0);Pc(void 0);const nu=Pc(null),kD=oe(Wc,n=>n.shape.length===1&&n.shape[0]===null);oe(Uint8Array);oe(Dp,n=>n.shape===Uint8Array);const UD=Fr(Mr,Kr,nu,Pb,Up,eu,Jb);(()=>{const n=Fb(kc),t=$b(Kr,kc),i=Fr(Mr,Kr,nu,eu,n,t);return n.shape=i,t.shape.values=i,i})();const Sl=n=>{if(xD.check(n))return n;if(SD.check(n)){const t={};for(const i in n)t[i]=Sl(n[i]);return yD(t)}else{if(ED.check(n))return Fr(...n.map(Sl));if(UD.check(n))return Pc(n);if(AD.check(n))return oe(n)}bn()},rv=eD?()=>{}:(n,t)=>{const i=new uD;if(!t.check(n,i))throw qn(`Expected value to be of type ${t.constructor.name}. +${i.toString()}`)};class zD{constructor(t){this.patterns=[],this.$state=t}if(t,i){return this.patterns.push({if:Sl(t),h:i}),this}else(t){return this.if(kc,t)}done(){return(t,i)=>{for(let r=0;rnew zD(n),tw=ND(kc).if(Zb,(n,t)=>id(t,XS,Oc)).if(Wb,(n,t)=>oD(t)).if(MD,(n,t)=>iv(t)).if(DD,(n,t)=>BigInt(id(t,XS,Oc))).if(Mc,(n,t)=>vr(t,rd(t,n.shape))).if(mD,(n,t)=>{const i={};for(const r in n.shape){let l=n.shape[r];if(pD.check(l)){if(iv(t))continue;l=l.shape}i[r]=tw(l,t)}return i}).if(wD,(n,t)=>{const i=[],r=Ib(t,0,42);for(let l=0;lrd(t,n.shape)).if(kD,(n,t)=>null).if(TD,(n,t)=>{const i=vr(t,n.res);return()=>i}).if(RD,(n,t)=>vr(t,rd(t,[Mr,Kr,nu,Pb,Up,eu,Fb(Mr),$b(Fr(`a`,`b`,`c`),Mr)]))).if(vD,(n,t)=>{const i={},r=id(t,0,3);for(let l=0;ltw(Sl(t),n),su=typeof document<`u`?document:{};ve(n=>n.nodeType===HD);typeof DOMParser<`u`&&new DOMParser;ve(n=>n.nodeType===BD);ve(n=>n.nodeType===LD);const jD=n=>rR(n,(t,i)=>`${i}:${t};`).join(``),BD=su.ELEMENT_NODE,LD=su.TEXT_NODE,ID=su.DOCUMENT_NODE,HD=su.DOCUMENT_FRAGMENT_NODE;ve(n=>n.nodeType===ID);const ms=Symbol,ew=ms(),nw=ms(),qD=ms(),KD=ms(),VD=ms(),sw=ms(),$D=ms(),zp=ms(),GD=ms(),YD=n=>{n.length===1&&n[0]?.constructor===Function&&(n=n[0]());const t=[],i=[];let r=0;for(;r0&&i.push(t.join(``));r{n.length===1&&n[0]?.constructor===Function&&(n=n[0]());const t=[],i=[],r=An();let l=[],o=0;for(;o0||p.length>0?(t.push(`%c`+u),i.push(p)):t.push(u)}else break}}for(o>0&&(l=i,l.unshift(t.join(``)));o{console.log(...iw(n)),rw.forEach(t=>t.print(n))},JD=(...n)=>{console.warn(...iw(n)),n.unshift(zp),rw.forEach(t=>t.print(n))},rw=Hr(),aw=n=>({[Symbol.iterator](){return this},next:n}),ZD=(n,t)=>aw(()=>{let i;do i=n.next();while(!i.done&&!t(i.value));return i}),ad=(n,t)=>aw(()=>{const{done:i,value:r}=n.next();return{done:i,value:i?void 0:t(r)}});class Np{constructor(t,i){this.clock=t,this.len=i}}class iu{constructor(){this.clients=new Map}}const lw=(n,t,i)=>t.clients.forEach((r,l)=>{const o=n.doc.store.clients.get(l);if(o!=null){const u=o[o.length-1],d=u.id.clock+u.length;for(let p=0,g=r[p];p{let i=0,r=n.length-1;for(;i<=r;){const l=Hn((i+r)/2),o=n[l],u=o.clock;if(u<=t){if(t{const i=n.clients.get(t.client);return i!==void 0&&WD(i,t.clock)!==null},jp=n=>{n.clients.forEach(t=>{t.sort((l,o)=>l.clock-o.clock);let i,r;for(i=1,r=1;i=o.clock?t[r-1]=new Np(l.clock,Yr(l.len,o.clock+o.len-l.clock)):(r{const t=new iu;for(let i=0;i{if(!t.clients.has(l)){const o=r.slice();for(let u=i+1;u{Ws(n.clients,t,()=>[]).push(new Np(i,r))},Bp=(n,t)=>{Dt(n.restEncoder,t.clients.size),Ei(t.clients.entries()).sort((i,r)=>r[0]-i[0]).forEach(([i,r])=>{n.resetDsCurVal(),Dt(n.restEncoder,i);const l=r.length;Dt(n.restEncoder,l);for(let o=0;o{const t=new iu,i=Ot(n.restDecoder);for(let r=0;r0){const u=Ws(t.clients,l,()=>[]);for(let d=0;d{const r=new iu,l=Ot(n.restDecoder);for(let o=0;o0){const o=new ru;return Dt(o.restEncoder,0),Bp(o,r),o.toUint8Array()}return null},cw=Ub;class Qr extends cR{constructor({guid:t=KR(),collectionid:i=null,gc:r=!0,gcFilter:l=()=>!0,meta:o=null,autoLoad:u=!1,shouldLoad:d=!0}={}){super(),this.gc=r,this.gcFilter=l,this.clientID=cw(),this.guid=t,this.collectionid=i,this.share=new Map,this.store=new dw,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=d,this.autoLoad=u,this.meta=o,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=nv(g=>{this.on(`load`,()=>{this.isLoaded=!0,g(this)})});const p=()=>nv(g=>{const y=m=>{(m===void 0||m===!0)&&(this.off(`sync`,y),g())};this.on(`sync`,y)});this.on(`sync`,g=>{g===!1&&this.isSynced&&(this.whenSynced=p()),this.isSynced=g===void 0||g===!0,this.isSynced&&!this.isLoaded&&this.emit(`load`,[this])}),this.whenSynced=p()}load(){const t=this._item;t!==null&&!this.shouldLoad&&$t(t.parent.doc,i=>{i.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(Ei(this.subdocs).map(t=>t.guid))}transact(t,i=null){return $t(this,t,i)}get(t,i=_e){const r=Ws(this.share,t,()=>{const o=new i;return o._integrate(this,null),o}),l=r.constructor;if(i!==_e&&l!==i)if(l===_e){const o=new i;o._map=r._map,r._map.forEach(u=>{for(;u!==null;u=u.left)u.parent=o}),o._start=r._start;for(let u=o._start;u!==null;u=u.right)u.parent=o;return o._length=r._length,this.share.set(t,o),o._integrate(this,null),o}else throw new Error(`Type with the name ${t} has already been defined with a different constructor`);return r}getArray(t=``){return this.get(t,Ur)}getText(t=``){return this.get(t,$r)}getMap(t=``){return this.get(t,Vr)}getXmlElement(t=``){return this.get(t,Gr)}getXmlFragment(t=``){return this.get(t,Ci)}toJSON(){const t={};return this.share.forEach((i,r)=>{t[r]=i.toJSON()}),t}destroy(){this.isDestroyed=!0,Ei(this.subdocs).forEach(i=>i.destroy());const t=this._item;if(t!==null){this._item=null;const i=t.content;i.doc=new Qr({guid:this.guid,...i.opts,shouldLoad:!1}),i.doc._item=t,$t(t.parent.doc,r=>{const l=i.doc;t.deleted||r.subdocsAdded.add(l),r.subdocsRemoved.add(this)},null,!0)}this.emit(`destroyed`,[!0]),this.emit(`destroy`,[this]),super.destroy()}}class eM{constructor(t){this.restDecoder=t}resetDsCurVal(){}readDsClock(){return Ot(this.restDecoder)}readDsLen(){return Ot(this.restDecoder)}}class nM extends eM{readLeftID(){return Rt(Ot(this.restDecoder),Ot(this.restDecoder))}readRightID(){return Rt(Ot(this.restDecoder),Ot(this.restDecoder))}readClient(){return Ot(this.restDecoder)}readInfo(){return qr(this.restDecoder)}readString(){return Dr(this.restDecoder)}readParentInfo(){return Ot(this.restDecoder)===1}readTypeRef(){return Ot(this.restDecoder)}readLen(){return Ot(this.restDecoder)}readAny(){return gl(this.restDecoder)}readBuf(){return rD(sn(this.restDecoder))}readJSON(){return JSON.parse(Dr(this.restDecoder))}readKey(){return Dr(this.restDecoder)}}class sM{constructor(t){this.dsCurrVal=0,this.restDecoder=t}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=Ot(this.restDecoder),this.dsCurrVal}readDsLen(){const t=Ot(this.restDecoder)+1;return this.dsCurrVal+=t,t}}class zc extends sM{constructor(t){super(t),this.keys=[],Ot(t),this.keyClockDecoder=new sd(sn(t)),this.clientDecoder=new pc(sn(t)),this.leftClockDecoder=new sd(sn(t)),this.rightClockDecoder=new sd(sn(t)),this.infoDecoder=new ev(sn(t),qr),this.stringDecoder=new IR(sn(t)),this.parentInfoDecoder=new ev(sn(t),qr),this.typeRefDecoder=new pc(sn(t)),this.lenDecoder=new pc(sn(t))}readLeftID(){return new kr(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new kr(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return gl(this.restDecoder)}readBuf(){return sn(this.restDecoder)}readJSON(){return gl(this.restDecoder)}readKey(){const t=this.keyClockDecoder.read();if(t{r=Yr(r,t[0].id.clock);const l=Kn(t,r);Dt(n.restEncoder,t.length-l),n.writeClient(i),Dt(n.restEncoder,r);const o=t[l];o.write(n,r-o.id.clock);for(let u=l+1;u{const r=new Map;i.forEach((l,o)=>{me(t,o)>l&&r.set(o,l)}),Lp(t).forEach((l,o)=>{i.has(o)||r.set(o,0)}),Dt(n.restEncoder,r.size),Ei(r.entries()).sort((l,o)=>o[0]-l[0]).forEach(([l,o])=>{lM(n,t.clients.get(l),l,o)})},oM=(n,t)=>{const i=An(),r=Ot(n.restDecoder);for(let l=0;l{const r=[];let l=Ei(i.keys()).sort((w,b)=>w-b);if(l.length===0)return null;const o=()=>{if(l.length===0)return null;let w=i.get(l[l.length-1]);for(;w.refs.length===w.i;)if(l.pop(),l.length>0)w=i.get(l[l.length-1]);else return null;return w};let u=o();if(u===null)return null;const d=new dw,p=new Map,g=(w,b)=>{const E=p.get(w);(E==null||E>b)&&p.set(w,b)};let y=u.refs[u.i++];const m=new Map,v=()=>{for(const w of r){const b=w.id.client,E=i.get(b);E?(E.i--,d.clients.set(b,E.refs.slice(E.i)),i.delete(b),E.i=0,E.refs=[]):d.clients.set(b,[w]),l=l.filter(_=>_!==b)}r.length=0};for(;;){if(y.constructor!==_n){const b=Ws(m,y.id.client,()=>me(t,y.id.client))-y.id.clock;if(b<0)r.push(y),g(y.id.client,y.id.clock-1),v();else{const E=y.getMissing(n,t);if(E!==null){r.push(y);const _=i.get(E)||{refs:[],i:0};if(_.refs.length===_.i)g(E,me(t,E)),v();else{y=_.refs[_.i++];continue}}else(b===0||b0)y=r.pop();else if(u!==null&&u.i0){const w=new ru;return uw(w,d,new Map),Dt(w.restEncoder,0),{missing:p,update:w.toUint8Array()}}return null},uM=(n,t)=>uw(n,t.doc.store,t.beforeState),fM=(n,t,i,r=new zc(n))=>$t(t,l=>{l.local=!1;let o=!1;const u=l.doc,d=u.store,p=oM(r,u),g=cM(l,d,p),y=d.pendingStructs;if(y){for(const[v,w]of y.missing)if(ww)&&y.missing.set(v,w)}y.update=pv([y.update,g.update])}}else d.pendingStructs=g;const m=av(r,l,d);if(d.pendingDs){const v=new zc(xp(d.pendingDs));Ot(v.restDecoder);const w=av(v,l,d);m&&w?d.pendingDs=pv([m,w]):d.pendingDs=m||w}else d.pendingDs=m;if(o){const v=d.pendingStructs.update;d.pendingStructs=null,fw(l.doc,v)}},i,!1),fw=(n,t,i,r=zc)=>{const l=xp(t);fM(l,n,i,new r(l))},lv=(n,t,i)=>fw(n,t,i,nM);class hM{constructor(){this.l=[]}}const ov=()=>new hM,cv=(n,t)=>n.l.push(t),uv=(n,t)=>{const i=n.l,r=i.length;n.l=i.filter(l=>t!==l),r===n.l.length&&console.error(`[yjs] Tried to remove event handler that doesn't exist.`)},hw=(n,t,i)=>Op(n.l,[t,i]);class kr{constructor(t,i){this.client=t,this.clock=i}}const ec=(n,t)=>n===t||n!==null&&t!==null&&n.client===t.client&&n.clock===t.clock,Rt=(n,t)=>new kr(n,t),dM=n=>{for(const[t,i]of n.doc.share.entries())if(i===n)return t;throw bn()},Cr=(n,t)=>t===void 0?!n.deleted:t.sv.has(n.id.client)&&(t.sv.get(n.id.client)||0)>n.id.clock&&!ow(t.ds,n.id),$d=(n,t)=>{const i=Ws(n.meta,$d,Hr),r=n.doc.store;i.has(t)||(t.sv.forEach((l,o)=>{l{}),i.add(t))};class dw{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const Lp=n=>{const t=new Map;return n.clients.forEach((i,r)=>{const l=i[i.length-1];t.set(r,l.id.clock+l.length)}),t},me=(n,t)=>{const i=n.clients.get(t);if(i===void 0)return 0;const r=i[i.length-1];return r.id.clock+r.length},pw=(n,t)=>{let i=n.clients.get(t.id.client);if(i===void 0)i=[],n.clients.set(t.id.client,i);else{const r=i[i.length-1];if(r.id.clock+r.length!==t.id.clock)throw bn()}i.push(t)},Kn=(n,t)=>{let i=0,r=n.length-1,l=n[r],o=l.id.clock;if(o===t)return r;let u=Hn(t/(o+l.length-1)*r);for(;i<=r;){if(l=n[u],o=l.id.clock,o<=t){if(t{const i=n.clients.get(t.client);return i[Kn(i,t.clock)]},ld=pM,Gd=(n,t,i)=>{const r=Kn(t,i),l=t[r];return l.id.clock{const i=n.doc.store.clients.get(t.client);return i[Gd(n,i,t.clock)]},fv=(n,t,i)=>{const r=t.clients.get(i.client),l=Kn(r,i.clock),o=r[l];return i.clock!==o.id.clock+o.length-1&&o.constructor!==vn&&r.splice(l+1,0,Hc(n,o,i.clock-o.id.clock+1)),o},gM=(n,t,i)=>{const r=n.clients.get(t.id.client);r[Kn(r,t.id.clock)]=i},gw=(n,t,i,r,l)=>{if(r===0)return;const o=i+r;let u=Gd(n,t,i),d;do d=t[u++],ot.deleteSet.clients.size===0&&!aR(t.afterState,(i,r)=>t.beforeState.get(r)!==i)?!1:(jp(t.deleteSet),uM(n,t),Bp(n,t.deleteSet),!0),dv=(n,t,i)=>{const r=t._item;(r===null||r.id.clock<(n.beforeState.get(r.id.client)||0)&&!r.deleted)&&Ws(n.changed,t,Hr).add(i)},yc=(n,t)=>{let i=n[t],r=n[t-1],l=t;for(;l>0;i=r,r=n[--l-1]){if(r.deleted===i.deleted&&r.constructor===i.constructor&&r.mergeWith(i)){i instanceof fe&&i.parentSub!==null&&i.parent._map.get(i.parentSub)===i&&i.parent._map.set(i.parentSub,r);continue}break}const o=t-l;return o&&n.splice(t+1-o,o),o},mM=(n,t,i)=>{for(const[r,l]of n.clients.entries()){const o=t.clients.get(r);for(let u=l.length-1;u>=0;u--){const d=l[u],p=d.clock+d.len;for(let g=Kn(o,d.clock),y=o[g];g{n.clients.forEach((i,r)=>{const l=t.clients.get(r);for(let o=i.length-1;o>=0;o--){const u=i[o],d=Rb(l.length-1,1+Kn(l,u.clock+u.len-1));for(let p=d,g=l[p];p>0&&g.id.clock>=u.clock;g=l[p])p-=1+yc(l,p)}})},yw=(n,t)=>{if(td.push(()=>{(g._item===null||!g._item.deleted)&&g._callObserver(i,p)})),d.push(()=>{i.changedParentTypes.forEach((p,g)=>{g._dEH.l.length>0&&(g._item===null||!g._item.deleted)&&(p=p.filter(y=>y.target._item===null||!y.target._item.deleted),p.forEach(y=>{y.currentTarget=g,y._path=null}),p.sort((y,m)=>y.path.length-m.path.length),d.push(()=>{hw(g._dEH,p,i)}))}),d.push(()=>r.emit(`afterTransaction`,[i,r])),d.push(()=>{i._needFormattingCleanup&&BM(i)})}),Op(d,[])}finally{r.gc&&mM(o,l,r.gcFilter),SM(o,l),i.afterState.forEach((y,m)=>{const v=i.beforeState.get(m)||0;if(v!==y){const w=l.clients.get(m),b=Yr(Kn(w,v),1);for(let E=w.length-1;E>=b;)E-=1+yc(w,E)}});for(let y=u.length-1;y>=0;y--){const{client:m,clock:v}=u[y].id,w=l.clients.get(m),b=Kn(w,v);b+11||b>0&&yc(w,b)}if(!i.local&&i.afterState.get(r.clientID)!==i.beforeState.get(r.clientID)&&(XD(zp,ew,`[yjs] `,nw,sw,`Changed the client-id because another client seems to be using it.`),r.clientID=cw()),r.emit(`afterTransactionCleanup`,[i,r]),r._observers.has(`update`)){const y=new rM;hv(y,i)&&r.emit(`update`,[y.toUint8Array(),i.origin,r,i])}if(r._observers.has(`updateV2`)){const y=new ru;hv(y,i)&&r.emit(`updateV2`,[y.toUint8Array(),i.origin,r,i])}const{subdocsAdded:d,subdocsLoaded:p,subdocsRemoved:g}=i;(d.size>0||g.size>0||p.size>0)&&(d.forEach(y=>{y.clientID=r.clientID,y.collectionid==null&&(y.collectionid=r.collectionid),r.subdocs.add(y)}),g.forEach(y=>r.subdocs.delete(y)),r.emit(`subdocs`,[{loaded:p,added:d,removed:g},r,i]),g.forEach(y=>y.destroy())),n.length<=t+1?(r._transactionCleanups=[],r.emit(`afterAllTransactions`,[r,n])):yw(n,t+1)}}},$t=(n,t,i=null,r=!0)=>{const l=n._transactionCleanups;let o=!1,u=null;n._transaction===null&&(o=!0,n._transaction=new yM(n,i,r),l.push(n._transaction),l.length===1&&n.emit(`beforeAllTransactions`,[n]),n.emit(`beforeTransaction`,[n._transaction,n]));try{u=t(n._transaction)}finally{if(o){const d=n._transaction===l[0];n._transaction=null,d&&yw(l,0)}}return u};function*vM(n){const t=Ot(n.restDecoder);for(let i=0;i{if(n.constructor===vn){const{client:i,clock:r}=n.id;return new vn(Rt(i,r+t),n.length-t)}else if(n.constructor===_n){const{client:i,clock:r}=n.id;return new _n(Rt(i,r+t),n.length-t)}else{const i=n,{client:r,clock:l}=i.id;return new fe(Rt(r,l+t),null,Rt(r,l+t-1),null,i.rightOrigin,i.parent,i.parentSub,i.content.splice(t))}},pv=(n,t=zc,i=ru)=>{if(n.length===1)return n[0];const r=n.map(y=>new t(xp(y)));let l=r.map(y=>new bM(y,!0)),o=null;const u=new i,d=new wM(u);for(;l=l.filter(v=>v.curr!==null),l.sort((v,w)=>{if(v.curr.id.client===w.curr.id.client){const b=v.curr.id.clock-w.curr.id.clock;return b===0?v.curr.constructor===w.curr.constructor?0:v.curr.constructor===_n?1:-1:b}else return w.curr.id.client-v.curr.id.client}),l.length!==0;){const y=l[0],m=y.curr.id.client;if(o!==null){let v=y.curr,w=!1;for(;v!==null&&v.id.clock+v.length<=o.struct.id.clock+o.struct.length&&v.id.client>=o.struct.id.client;)v=y.next(),w=!0;if(v===null||v.id.client!==m||w&&v.id.clock>o.struct.id.clock+o.struct.length)continue;if(m!==o.struct.id.client)Fa(d,o.struct,o.offset),o={struct:v,offset:0},y.next();else if(o.struct.id.clock+o.struct.length0&&(o.struct.constructor===_n?o.struct.length-=b:v=EM(v,b)),o.struct.mergeWith(v)||(Fa(d,o.struct,o.offset),o={struct:v,offset:0},y.next())}}else o={struct:y.curr,offset:0},y.next();for(let v=y.curr;v!==null&&v.id.client===m&&v.id.clock===o.struct.id.clock+o.struct.length&&v.constructor!==_n;v=y.next())Fa(d,o.struct,o.offset),o={struct:v,offset:0}}o!==null&&(Fa(d,o.struct,o.offset),o=null),CM(d);const p=r.map(y=>tM(y)),g=PD(p);return Bp(u,g),u.toUint8Array()},mw=n=>{n.written>0&&(n.clientStructs.push({written:n.written,restEncoder:In(n.encoder.restEncoder)}),n.encoder.restEncoder=Xc(),n.written=0)},Fa=(n,t,i)=>{n.written>0&&n.currClient!==t.id.client&&mw(n),n.written===0&&(n.currClient=t.id.client,n.encoder.writeClient(t.id.client),Dt(n.encoder.restEncoder,t.id.clock+i)),t.write(n.encoder,i),n.written++},CM=n=>{mw(n);const t=n.encoder.restEncoder;Dt(t,n.clientStructs.length);for(let i=0;i{if(l!==null){const o=i._map.get(l);let u,d;if(this.adds(o)){let p=o.left;for(;p!==null&&this.adds(p);)p=p.left;if(this.deletes(o))if(p!==null&&this.deletes(p))u=`delete`,d=Ph(p.content.getContent());else return;else p!==null&&this.deletes(p)?(u=`update`,d=Ph(p.content.getContent())):(u=`add`,d=void 0)}else if(this.deletes(o))u=`delete`,d=Ph(o.content.getContent());else return;t.set(l,{action:u,oldValue:d})}}),this._keys=t}return this._keys}get delta(){return this.changes.delta}adds(t){return t.id.clock>=(this.transaction.beforeState.get(t.id.client)||0)}get changes(){let t=this._changes;if(t===null){if(this.transaction.doc._transactionCleanups.length===0)throw qn(gv);const i=this.target,r=Hr(),l=Hr(),o=[];if(t={added:r,deleted:l,delta:o,keys:this.keys},this.transaction.changed.get(i).has(null)){let d=null;const p=()=>{d&&o.push(d)};for(let g=i._start;g!==null;g=g.right)g.deleted?this.deletes(g)&&!this.adds(g)&&((d===null||d.delete===void 0)&&(p(),d={delete:0}),d.delete+=g.length,l.add(g)):this.adds(g)?((d===null||d.insert===void 0)&&(p(),d={insert:[]}),d.insert=d.insert.concat(g.content.getContent()),r.add(g)):((d===null||d.retain===void 0)&&(p(),d={retain:0}),d.retain+=g.length);d!==null&&d.retain===void 0&&p()}this._changes=t}return t}}const xM=(n,t)=>{const i=[];for(;t._item!==null&&t!==n;){if(t._item.parentSub!==null)i.unshift(t._item.parentSub);else{let r=0,l=t._item.parent._start;for(;l!==t._item&&l!==null;)!l.deleted&&l.countable&&(r+=l.length),l=l.right;i.unshift(r)}t=t._item.parent}return i},Re=()=>{JD(`Invalid access: Add Yjs type to a document before reading data.`)},Sw=80;let Ip=0;class _M{constructor(t,i){t.marker=!0,this.p=t,this.index=i,this.timestamp=Ip++}}const TM=n=>{n.timestamp=Ip++},vw=(n,t,i)=>{n.p.marker=!1,n.p=t,t.marker=!0,n.index=i,n.timestamp=Ip++},AM=(n,t,i)=>{if(n.length>=Sw){const r=n.reduce((l,o)=>l.timestamp{if(n._start===null||t===0||n._searchMarker===null)return null;const i=n._searchMarker.length===0?null:n._searchMarker.reduce((o,u)=>hc(t-o.index)t;)r=r.left,!r.deleted&&r.countable&&(l-=r.length);for(;r.left!==null&&r.left.id.client===r.id.client&&r.left.id.clock+r.left.length===r.id.clock;)r=r.left,!r.deleted&&r.countable&&(l-=r.length);return i!==null&&hc(i.index-l){for(let r=n.length-1;r>=0;r--){const l=n[r];if(i>0){let o=l.p;for(o.marker=!1;o&&(o.deleted||!o.countable);)o=o.left,o&&!o.deleted&&o.countable&&(l.index-=o.length);if(o===null||o.marker===!0){n.splice(r,1);continue}l.p=o,o.marker=!0}(t0&&t===l.index)&&(l.index=Yr(t,l.index+i))}},ou=(n,t,i)=>{const r=n,l=t.changedParentTypes;for(;Ws(l,n,()=>[]).push(i),n._item!==null;)n=n._item.parent;hw(r._eH,i,t)};class _e{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=ov(),this._dEH=ov(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(t,i){this.doc=t,this._item=i}_copy(){throw On()}clone(){throw On()}_write(t){}get _first(){let t=this._start;for(;t!==null&&t.deleted;)t=t.right;return t}_callObserver(t,i){!t.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(t){cv(this._eH,t)}observeDeep(t){cv(this._dEH,t)}unobserve(t){uv(this._eH,t)}unobserveDeep(t){uv(this._dEH,t)}toJSON(){}}const bw=(n,t,i)=>{n.doc??Re(),t<0&&(t=n._length+t),i<0&&(i=n._length+i);let r=i-t;const l=[];let o=n._start;for(;o!==null&&r>0;){if(o.countable&&!o.deleted){const u=o.content.getContent();if(u.length<=t)t-=u.length;else{for(let d=t;d0;d++)l.push(u[d]),r--;t=0}}o=o.right}return l},ww=n=>{n.doc??Re();const t=[];let i=n._start;for(;i!==null;){if(i.countable&&!i.deleted){const r=i.content.getContent();for(let l=0;l{let i=0,r=n._start;for(n.doc??Re();r!==null;){if(r.countable&&!r.deleted){const l=r.content.getContent();for(let o=0;o{const i=[];return bl(n,(r,l)=>{i.push(t(r,l,n))}),i},OM=n=>{let t=n._start,i=null,r=0;return{[Symbol.iterator](){return this},next:()=>{if(i===null){for(;t!==null&&t.deleted;)t=t.right;if(t===null)return{done:!0,value:void 0};i=t.content.getContent(),r=0,t=t.right}const l=i[r++];return i.length<=r&&(i=null),{done:!1,value:l}}}},Cw=(n,t)=>{n.doc??Re();const i=lu(n,t);let r=n._start;for(i!==null&&(r=i.p,t-=i.index);r!==null;r=r.right)if(!r.deleted&&r.countable){if(t{let l=i;const o=n.doc,u=o.clientID,d=o.store,p=i===null?t._start:i.right;let g=[];const y=()=>{g.length>0&&(l=new fe(Rt(u,me(d,u)),l,l&&l.lastId,p,p&&p.id,t,null,new xi(g)),l.integrate(n,0),g=[])};r.forEach(m=>{if(m===null)g.push(m);else switch(m.constructor){case Number:case Object:case Boolean:case Array:case String:g.push(m);break;default:switch(y(),m.constructor){case Uint8Array:case ArrayBuffer:l=new fe(Rt(u,me(d,u)),l,l&&l.lastId,p,p&&p.id,t,null,new Ol(new Uint8Array(m))),l.integrate(n,0);break;case Qr:l=new fe(Rt(u,me(d,u)),l,l&&l.lastId,p,p&&p.id,t,null,new Rl(m)),l.integrate(n,0);break;default:if(m instanceof _e)l=new fe(Rt(u,me(d,u)),l,l&&l.lastId,p,p&&p.id,t,null,new Ss(m)),l.integrate(n,0);else throw new Error(`Unexpected content type in insert operation`)}}}),y()},xw=()=>qn(`Length exceeded!`),_w=(n,t,i,r)=>{if(i>t._length)throw xw();if(i===0)return t._searchMarker&&vl(t._searchMarker,i,r.length),Nc(n,t,null,r);const l=i,o=lu(t,i);let u=t._start;for(o!==null&&(u=o.p,i-=o.index,i===0&&(u=u.prev,i+=u&&u.countable&&!u.deleted?u.length:0));u!==null;u=u.right)if(!u.deleted&&u.countable){if(i<=u.length){i{let l=(t._searchMarker||[]).reduce((o,u)=>u.index>o.index?u:o,{index:0,p:t._start}).p;if(l)for(;l.right;)l=l.right;return Nc(n,t,l,i)},Tw=(n,t,i,r)=>{if(r===0)return;const l=i,o=r,u=lu(t,i);let d=t._start;for(u!==null&&(d=u.p,i-=u.index);d!==null&&i>0;d=d.right)!d.deleted&&d.countable&&(i0&&d!==null;)d.deleted||(r0)throw xw();t._searchMarker&&vl(t._searchMarker,l,-o+r)},jc=(n,t,i)=>{const r=t._map.get(i);r!==void 0&&r.delete(n)},Hp=(n,t,i,r)=>{const l=t._map.get(i)||null,o=n.doc,u=o.clientID;let d;if(r==null)d=new xi([r]);else switch(r.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:d=new xi([r]);break;case Uint8Array:d=new Ol(r);break;case Qr:d=new Rl(r);break;default:if(r instanceof _e)d=new Ss(r);else throw new Error(`Unexpected content type`)}new fe(Rt(u,me(o.store,u)),l,l&&l.lastId,null,null,t,i,d).integrate(n,0)},qp=(n,t)=>{n.doc??Re();const i=n._map.get(t);return i!==void 0&&!i.deleted?i.content.getContent()[i.length-1]:void 0},Aw=n=>{const t={};return n.doc??Re(),n._map.forEach((i,r)=>{i.deleted||(t[r]=i.content.getContent()[i.length-1])}),t},Ow=(n,t)=>{n.doc??Re();const i=n._map.get(t);return i!==void 0&&!i.deleted},DM=(n,t)=>{const i={};return n._map.forEach((r,l)=>{let o=r;for(;o!==null&&(!t.sv.has(o.id.client)||o.id.clock>=(t.sv.get(o.id.client)||0));)o=o.left;o!==null&&Cr(o,t)&&(i[l]=o.content.getContent()[o.length-1])}),i},nc=n=>(n.doc??Re(),ZD(n._map.entries(),t=>!t[1].deleted));class MM extends au{}class Ur extends _e{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(t){const i=new Ur;return i.push(t),i}_integrate(t,i){super._integrate(t,i),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new Ur}clone(){const t=new Ur;return t.insert(0,this.toArray().map(i=>i instanceof _e?i.clone():i)),t}get length(){return this.doc??Re(),this._length}_callObserver(t,i){super._callObserver(t,i),ou(this,t,new MM(this,t))}insert(t,i){this.doc!==null?$t(this.doc,r=>{_w(r,this,t,i)}):this._prelimContent.splice(t,0,...i)}push(t){this.doc!==null?$t(this.doc,i=>{RM(i,this,t)}):this._prelimContent.push(...t)}unshift(t){this.insert(0,t)}delete(t,i=1){this.doc!==null?$t(this.doc,r=>{Tw(r,this,t,i)}):this._prelimContent.splice(t,i)}get(t){return Cw(this,t)}toArray(){return ww(this)}slice(t=0,i=this.length){return bw(this,t,i)}toJSON(){return this.map(t=>t instanceof _e?t.toJSON():t)}map(t){return Ew(this,t)}forEach(t){bl(this,t)}[Symbol.iterator](){return OM(this)}_write(t){t.writeTypeRef(n2)}}const kM=n=>new Ur;class UM extends au{constructor(t,i,r){super(t,i),this.keysChanged=r}}class Vr extends _e{constructor(t){super(),this._prelimContent=null,t===void 0?this._prelimContent=new Map:this._prelimContent=new Map(t)}_integrate(t,i){super._integrate(t,i),this._prelimContent.forEach((r,l)=>{this.set(l,r)}),this._prelimContent=null}_copy(){return new Vr}clone(){const t=new Vr;return this.forEach((i,r)=>{t.set(r,i instanceof _e?i.clone():i)}),t}_callObserver(t,i){ou(this,t,new UM(this,t,i))}toJSON(){this.doc??Re();const t={};return this._map.forEach((i,r)=>{if(!i.deleted){const l=i.content.getContent()[i.length-1];t[r]=l instanceof _e?l.toJSON():l}}),t}get size(){return[...nc(this)].length}keys(){return ad(nc(this),t=>t[0])}values(){return ad(nc(this),t=>t[1].content.getContent()[t[1].length-1])}entries(){return ad(nc(this),t=>[t[0],t[1].content.getContent()[t[1].length-1]])}forEach(t){this.doc??Re(),this._map.forEach((i,r)=>{i.deleted||t(i.content.getContent()[i.length-1],r,this)})}[Symbol.iterator](){return this.entries()}delete(t){this.doc!==null?$t(this.doc,i=>{jc(i,this,t)}):this._prelimContent.delete(t)}set(t,i){return this.doc!==null?$t(this.doc,r=>{Hp(r,this,t,i)}):this._prelimContent.set(t,i),i}get(t){return qp(this,t)}has(t){return Ow(this,t)}clear(){this.doc!==null?$t(this.doc,t=>{this.forEach(function(i,r,l){jc(t,l,r)})}):this._prelimContent.clear()}_write(t){t.writeTypeRef(s2)}}const zM=n=>new Vr,Qs=(n,t)=>n===t||typeof n==`object`&&typeof t==`object`&&n&&t&&ZR(n,t);class Yd{constructor(t,i,r,l){this.left=t,this.right=i,this.index=r,this.currentAttributes=l}forward(){switch(this.right===null&&bn(),this.right.content.constructor){case he:this.right.deleted||Xr(this.currentAttributes,this.right.content);break;default:this.right.deleted||(this.index+=this.right.length);break}this.left=this.right,this.right=this.right.right}}const yv=(n,t,i)=>{for(;t.right!==null&&i>0;){switch(t.right.content.constructor){case he:t.right.deleted||Xr(t.currentAttributes,t.right.content);break;default:t.right.deleted||(i{const l=new Map,o=r?lu(t,i):null;if(o){const u=new Yd(o.p.left,o.p,o.index,l);return yv(n,u,i-o.index)}else{const u=new Yd(null,t._start,0,l);return yv(n,u,i)}},Rw=(n,t,i,r)=>{for(;i.right!==null&&(i.right.deleted===!0||i.right.content.constructor===he&&Qs(r.get(i.right.content.key),i.right.content.value));)i.right.deleted||r.delete(i.right.content.key),i.forward();const l=n.doc,o=l.clientID;r.forEach((u,d)=>{const p=i.left,g=i.right,y=new fe(Rt(o,me(l.store,o)),p,p&&p.lastId,g,g&&g.id,t,null,new he(d,u));y.integrate(n,0),i.right=y,i.forward()})},Xr=(n,t)=>{const{key:i,value:r}=t;r===null?n.delete(i):n.set(i,r)},Dw=(n,t)=>{for(;n.right!==null;){if(!(n.right.deleted||n.right.content.constructor===he&&Qs(t[n.right.content.key]??null,n.right.content.value)))break;n.forward()}},Mw=(n,t,i,r)=>{const l=n.doc,o=l.clientID,u=new Map;for(const d in r){const p=r[d],g=i.currentAttributes.get(d)??null;if(!Qs(g,p)){u.set(d,g);const{left:y,right:m}=i;i.right=new fe(Rt(o,me(l.store,o)),y,y&&y.lastId,m,m&&m.id,t,null,new he(d,p)),i.right.integrate(n,0),i.forward()}}return u},od=(n,t,i,r,l)=>{i.currentAttributes.forEach((v,w)=>{l[w]===void 0&&(l[w]=null)});const o=n.doc,u=o.clientID;Dw(i,l);const d=Mw(n,t,i,l),p=r.constructor===String?new Vn(r):r instanceof _e?new Ss(r):new Mi(r);let{left:g,right:y,index:m}=i;t._searchMarker&&vl(t._searchMarker,i.index,p.getLength()),y=new fe(Rt(u,me(o.store,u)),g,g&&g.lastId,y,y&&y.id,t,null,p),y.integrate(n,0),i.right=y,i.index=m,i.forward(),Rw(n,t,i,d)},mv=(n,t,i,r,l)=>{const o=n.doc,u=o.clientID;Dw(i,l);const d=Mw(n,t,i,l);t:for(;i.right!==null&&(r>0||d.size>0&&(i.right.deleted||i.right.content.constructor===he));){if(!i.right.deleted)switch(i.right.content.constructor){case he:{const{key:p,value:g}=i.right.content,y=l[p];if(y!==void 0){if(Qs(y,g))d.delete(p);else{if(r===0)break t;d.set(p,g)}i.right.delete(n)}else i.currentAttributes.set(p,g);break}default:r0){let p=``;for(;r>0;r--)p+=` +`;i.right=new fe(Rt(u,me(o.store,u)),i.left,i.left&&i.left.lastId,i.right,i.right&&i.right.id,t,null,new Vn(p)),i.right.integrate(n,0),i.forward()}Rw(n,t,i,d)},kw=(n,t,i,r,l)=>{let o=t;const u=An();for(;o&&(!o.countable||o.deleted);){if(!o.deleted&&o.content.constructor===he){const g=o.content;u.set(g.key,g)}o=o.right}let d=0,p=!1;for(;t!==o;){if(i===t&&(p=!0),!t.deleted){const g=t.content;switch(g.constructor){case he:{const{key:y,value:m}=g,v=r.get(y)??null;(u.get(y)!==g||v===m)&&(t.delete(n),d++,!p&&(l.get(y)??null)===m&&v!==m&&(v===null?l.delete(y):l.set(y,v))),!p&&!t.deleted&&Xr(l,g);break}}}t=t.right}return d},NM=(n,t)=>{for(;t&&t.right&&(t.right.deleted||!t.right.countable);)t=t.right;const i=new Set;for(;t&&(t.deleted||!t.countable);){if(!t.deleted&&t.content.constructor===he){const r=t.content.key;i.has(r)?t.delete(n):i.add(r)}t=t.left}},jM=n=>{let t=0;return $t(n.doc,i=>{let r=n._start,l=n._start,o=An();const u=Ld(o);for(;l;){if(l.deleted===!1)switch(l.content.constructor){case he:Xr(u,l.content);break;default:t+=kw(i,r,l,o,u),o=Ld(u),r=l;break}l=l.right}}),t},BM=n=>{const t=new Set,i=n.doc;for(const[r,l]of n.afterState.entries()){const o=n.beforeState.get(r)||0;l!==o&&gw(n,i.store.clients.get(r),o,l,u=>{!u.deleted&&u.content.constructor===he&&u.constructor!==vn&&t.add(u.parent)})}$t(i,r=>{lw(n,n.deleteSet,l=>{if(l instanceof vn||!l.parent._hasFormatting||t.has(l.parent))return;const o=l.parent;l.content.constructor===he?t.add(o):NM(r,l)});for(const l of t)jM(l)})},Sv=(n,t,i)=>{const r=i,l=Ld(t.currentAttributes),o=t.right;for(;i>0&&t.right!==null;){if(t.right.deleted===!1)switch(t.right.content.constructor){case Ss:case Mi:case Vn:i{l===null?this.childListChanged=!0:this.keysChanged.add(l)})}get changes(){if(this._changes===null){const t={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=t}return this._changes}get delta(){if(this._delta===null){const t=this.target.doc,i=[];$t(t,r=>{const l=new Map,o=new Map;let u=this.target._start,d=null;const p={};let g=``,y=0,m=0;const v=()=>{if(d!==null){let w=null;switch(d){case`delete`:m>0&&(w={delete:m}),m=0;break;case`insert`:(typeof g==`object`||g.length>0)&&(w={insert:g},l.size>0&&(w.attributes={},l.forEach((b,E)=>{b!==null&&(w.attributes[E]=b)}))),g=``;break;case`retain`:y>0&&(w={retain:y},JR(p)||(w.attributes=FR({},p))),y=0;break}w&&i.push(w),d=null}};for(;u!==null;){switch(u.content.constructor){case Ss:case Mi:this.adds(u)?this.deletes(u)||(v(),d=`insert`,g=u.content.getContent()[0],v()):this.deletes(u)?(d!==`delete`&&(v(),d=`delete`),m+=1):u.deleted||(d!==`retain`&&(v(),d=`retain`),y+=1);break;case Vn:this.adds(u)?this.deletes(u)||(d!==`insert`&&(v(),d=`insert`),g+=u.content.str):this.deletes(u)?(d!==`delete`&&(v(),d=`delete`),m+=u.length):u.deleted||(d!==`retain`&&(v(),d=`retain`),y+=u.length);break;case he:{const{key:w,value:b}=u.content;if(this.adds(u)){if(!this.deletes(u)){const E=l.get(w)??null;Qs(E,b)?b!==null&&u.delete(r):(d===`retain`&&v(),Qs(b,o.get(w)??null)?delete p[w]:p[w]=b)}}else if(this.deletes(u)){o.set(w,b);const E=l.get(w)??null;Qs(E,b)||(d===`retain`&&v(),p[w]=E)}else if(!u.deleted){o.set(w,b);const E=p[w];E!==void 0&&(Qs(E,b)?E!==null&&u.delete(r):(d===`retain`&&v(),b===null?delete p[w]:p[w]=b))}u.deleted||(d===`insert`&&v(),Xr(l,u.content));break}}u=u.right}for(v();i.length>0;){const w=i[i.length-1];if(w.retain!==void 0&&w.attributes===void 0)i.pop();else break}}),this._delta=i}return this._delta}}class $r extends _e{constructor(t){super(),this._pending=t!==void 0?[()=>this.insert(0,t)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??Re(),this._length}_integrate(t,i){super._integrate(t,i);try{this._pending.forEach(r=>r())}catch(r){console.error(r)}this._pending=null}_copy(){return new $r}clone(){const t=new $r;return t.applyDelta(this.toDelta()),t}_callObserver(t,i){super._callObserver(t,i);const r=new LM(this,t,i);ou(this,t,r),!t.local&&this._hasFormatting&&(t._needFormattingCleanup=!0)}toString(){this.doc??Re();let t=``,i=this._start;for(;i!==null;)!i.deleted&&i.countable&&i.content.constructor===Vn&&(t+=i.content.str),i=i.right;return t}toJSON(){return this.toString()}applyDelta(t,{sanitize:i=!0}={}){this.doc!==null?$t(this.doc,r=>{const l=new Yd(null,this._start,0,new Map);for(let o=0;o0)&&od(r,this,l,d,u.attributes||{})}else u.retain!==void 0?mv(r,this,l,u.retain,u.attributes||{}):u.delete!==void 0&&Sv(r,l,u.delete)}}):this._pending.push(()=>this.applyDelta(t))}toDelta(t,i,r){this.doc??Re();const l=[],o=new Map,u=this.doc;let d=``,p=this._start;function g(){if(d.length>0){const m={};let v=!1;o.forEach((b,E)=>{v=!0,m[E]=b});const w={insert:d};v&&(w.attributes=m),l.push(w),d=``}}const y=()=>{for(;p!==null;){if(Cr(p,t)||i!==void 0&&Cr(p,i))switch(p.content.constructor){case Vn:{const m=o.get(`ychange`);t!==void 0&&!Cr(p,t)?(m===void 0||m.user!==p.id.client||m.type!==`removed`)&&(g(),o.set(`ychange`,r?r(`removed`,p.id):{type:`removed`})):i!==void 0&&!Cr(p,i)?(m===void 0||m.user!==p.id.client||m.type!==`added`)&&(g(),o.set(`ychange`,r?r(`added`,p.id):{type:`added`})):m!==void 0&&(g(),o.delete(`ychange`)),d+=p.content.str;break}case Ss:case Mi:{g();const m={insert:p.content.getContent()[0]};if(o.size>0){const v={};m.attributes=v,o.forEach((w,b)=>{v[b]=w})}l.push(m);break}case he:Cr(p,t)&&(g(),Xr(o,p.content));break}p=p.right}g()};return t||i?$t(u,m=>{t&&$d(m,t),i&&$d(m,i),y()},`cleanup`):y(),l}insert(t,i,r){if(i.length<=0)return;const l=this.doc;l!==null?$t(l,o=>{const u=sc(o,this,t,!r);r||(r={},u.currentAttributes.forEach((d,p)=>{r[p]=d})),od(o,this,u,i,r)}):this._pending.push(()=>this.insert(t,i,r))}insertEmbed(t,i,r){const l=this.doc;l!==null?$t(l,o=>{const u=sc(o,this,t,!r);od(o,this,u,i,r||{})}):this._pending.push(()=>this.insertEmbed(t,i,r||{}))}delete(t,i){if(i===0)return;const r=this.doc;r!==null?$t(r,l=>{Sv(l,sc(l,this,t,!0),i)}):this._pending.push(()=>this.delete(t,i))}format(t,i,r){if(i===0)return;const l=this.doc;l!==null?$t(l,o=>{const u=sc(o,this,t,!1);u.right!==null&&mv(o,this,u,i,r)}):this._pending.push(()=>this.format(t,i,r))}removeAttribute(t){this.doc!==null?$t(this.doc,i=>{jc(i,this,t)}):this._pending.push(()=>this.removeAttribute(t))}setAttribute(t,i){this.doc!==null?$t(this.doc,r=>{Hp(r,this,t,i)}):this._pending.push(()=>this.setAttribute(t,i))}getAttribute(t){return qp(this,t)}getAttributes(){return Aw(this)}_write(t){t.writeTypeRef(i2)}}const IM=n=>new $r;class cd{constructor(t,i=()=>!0){this._filter=i,this._root=t,this._currentNode=t._start,this._firstCall=!0,t.doc??Re()}[Symbol.iterator](){return this}next(){let t=this._currentNode,i=t&&t.content&&t.content.type;if(t!==null&&(!this._firstCall||t.deleted||!this._filter(i)))do if(i=t.content.type,!t.deleted&&(i.constructor===Gr||i.constructor===Ci)&&i._start!==null)t=i._start;else for(;t!==null;){const r=t.next;if(r!==null){t=r;break}else t.parent===this._root?t=null:t=t.parent._item}while(t!==null&&(t.deleted||!this._filter(t.content.type)));return this._firstCall=!1,t===null?{value:void 0,done:!0}:(this._currentNode=t,{value:t.content.type,done:!1})}}class Ci extends _e{constructor(){super(),this._prelimContent=[]}get firstChild(){const t=this._first;return t?t.content.getContent()[0]:null}_integrate(t,i){super._integrate(t,i),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new Ci}clone(){const t=new Ci;return t.insert(0,this.toArray().map(i=>i instanceof _e?i.clone():i)),t}get length(){return this.doc??Re(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(t){return new cd(this,t)}querySelector(t){t=t.toUpperCase();const r=new cd(this,l=>l.nodeName&&l.nodeName.toUpperCase()===t).next();return r.done?null:r.value}querySelectorAll(t){return t=t.toUpperCase(),Ei(new cd(this,i=>i.nodeName&&i.nodeName.toUpperCase()===t))}_callObserver(t,i){ou(this,t,new KM(this,i,t))}toString(){return Ew(this,t=>t.toString()).join(``)}toJSON(){return this.toString()}toDOM(t=document,i={},r){const l=t.createDocumentFragment();return r!==void 0&&r._createAssociation(l,this),bl(this,o=>{l.insertBefore(o.toDOM(t,i,r),null)}),l}insert(t,i){this.doc!==null?$t(this.doc,r=>{_w(r,this,t,i)}):this._prelimContent.splice(t,0,...i)}insertAfter(t,i){if(this.doc!==null)$t(this.doc,r=>{const l=t&&t instanceof _e?t._item:t;Nc(r,this,l,i)});else{const r=this._prelimContent,l=t===null?0:r.findIndex(o=>o===t)+1;if(l===0&&t!==null)throw qn(`Reference item not found`);r.splice(l,0,...i)}}delete(t,i=1){this.doc!==null?$t(this.doc,r=>{Tw(r,this,t,i)}):this._prelimContent.splice(t,i)}toArray(){return ww(this)}push(t){this.insert(this.length,t)}unshift(t){this.insert(0,t)}get(t){return Cw(this,t)}slice(t=0,i=this.length){return bw(this,t,i)}forEach(t){bl(this,t)}_write(t){t.writeTypeRef(a2)}}const HM=n=>new Ci;class Gr extends Ci{constructor(t=`UNDEFINED`){super(),this.nodeName=t,this._prelimAttrs=new Map}get nextSibling(){const t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){const t=this._item?this._item.prev:null;return t?t.content.type:null}_integrate(t,i){super._integrate(t,i),this._prelimAttrs.forEach((r,l)=>{this.setAttribute(l,r)}),this._prelimAttrs=null}_copy(){return new Gr(this.nodeName)}clone(){const t=new Gr(this.nodeName),i=this.getAttributes();return XR(i,(r,l)=>{t.setAttribute(l,r)}),t.insert(0,this.toArray().map(r=>r instanceof _e?r.clone():r)),t}toString(){const t=this.getAttributes(),i=[],r=[];for(const d in t)r.push(d);r.sort();const l=r.length;for(let d=0;d0?` `+i.join(` `):``;return`<${o}${u}>${super.toString()}`}removeAttribute(t){this.doc!==null?$t(this.doc,i=>{jc(i,this,t)}):this._prelimAttrs.delete(t)}setAttribute(t,i){this.doc!==null?$t(this.doc,r=>{Hp(r,this,t,i)}):this._prelimAttrs.set(t,i)}getAttribute(t){return qp(this,t)}hasAttribute(t){return Ow(this,t)}getAttributes(t){return t?DM(this,t):Aw(this)}toDOM(t=document,i={},r){const l=t.createElement(this.nodeName),o=this.getAttributes();for(const u in o){const d=o[u];typeof d==`string`&&l.setAttribute(u,d)}return bl(this,u=>{l.appendChild(u.toDOM(t,i,r))}),r!==void 0&&r._createAssociation(l,this),l}_write(t){t.writeTypeRef(r2),t.writeKey(this.nodeName)}}const qM=n=>new Gr(n.readKey());class KM extends au{constructor(t,i,r){super(t,r),this.childListChanged=!1,this.attributesChanged=new Set,i.forEach(l=>{l===null?this.childListChanged=!0:this.attributesChanged.add(l)})}}class Bc extends Vr{constructor(t){super(),this.hookName=t}_copy(){return new Bc(this.hookName)}clone(){const t=new Bc(this.hookName);return this.forEach((i,r)=>{t.set(r,i)}),t}toDOM(t=document,i={},r){const l=i[this.hookName];let o;return l!==void 0?o=l.createDom(this):o=document.createElement(this.hookName),o.setAttribute(`data-yjs-hook`,this.hookName),r!==void 0&&r._createAssociation(o,this),o}_write(t){t.writeTypeRef(l2),t.writeKey(this.hookName)}}const VM=n=>new Bc(n.readKey());class Lc extends $r{get nextSibling(){const t=this._item?this._item.next:null;return t?t.content.type:null}get prevSibling(){const t=this._item?this._item.prev:null;return t?t.content.type:null}_copy(){return new Lc}clone(){const t=new Lc;return t.applyDelta(this.toDelta()),t}toDOM(t=document,i,r){const l=t.createTextNode(this.toString());return r!==void 0&&r._createAssociation(l,this),l}toString(){return this.toDelta().map(t=>{const i=[];for(const l in t.attributes){const o=[];for(const u in t.attributes[l])o.push({key:u,value:t.attributes[l][u]});o.sort((u,d)=>u.keyl.nodeName`}r+=t.insert;for(let l=i.length-1;l>=0;l--)r+=``;return r}).join(``)}toJSON(){return this.toString()}_write(t){t.writeTypeRef(o2)}}const $M=n=>new Lc;class Kp{constructor(t,i){this.id=t,this.length=i}get deleted(){throw On()}mergeWith(t){return!1}write(t,i,r){throw On()}integrate(t,i){throw On()}}const GM=0;class vn extends Kp{get deleted(){return!0}delete(){}mergeWith(t){return this.constructor!==t.constructor?!1:(this.length+=t.length,!0)}integrate(t,i){i>0&&(this.id.clock+=i,this.length-=i),pw(t.doc.store,this)}write(t,i){t.writeInfo(GM),t.writeLen(this.length-i)}getMissing(t,i){return null}}class Ol{constructor(t){this.content=t}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new Ol(this.content)}splice(t){throw On()}mergeWith(t){return!1}integrate(t,i){}delete(t){}gc(t){}write(t,i){t.writeBuf(this.content)}getRef(){return 3}}const YM=n=>new Ol(n.readBuf());class wl{constructor(t){this.len=t}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new wl(this.len)}splice(t){const i=new wl(this.len-t);return this.len=t,i}mergeWith(t){return this.len+=t.len,!0}integrate(t,i){Uc(t.deleteSet,i.id.client,i.id.clock,this.len),i.markDeleted()}delete(t){}gc(t){}write(t,i){t.writeLen(this.len-i)}getRef(){return 1}}const FM=n=>new wl(n.readLen()),Uw=(n,t)=>new Qr({guid:n,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1});class Rl{constructor(t){t._item&&console.error(`This document was already integrated as a sub-document. You should create a second instance instead with the same guid.`),this.doc=t;const i={};this.opts=i,t.gc||(i.gc=!1),t.autoLoad&&(i.autoLoad=!0),t.meta!==null&&(i.meta=t.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new Rl(Uw(this.doc.guid,this.opts))}splice(t){throw On()}mergeWith(t){return!1}integrate(t,i){this.doc._item=i,t.subdocsAdded.add(this.doc),this.doc.shouldLoad&&t.subdocsLoaded.add(this.doc)}delete(t){t.subdocsAdded.has(this.doc)?t.subdocsAdded.delete(this.doc):t.subdocsRemoved.add(this.doc)}gc(t){}write(t,i){t.writeString(this.doc.guid),t.writeAny(this.opts)}getRef(){return 9}}const QM=n=>new Rl(Uw(n.readString(),n.readAny()));class Mi{constructor(t){this.embed=t}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new Mi(this.embed)}splice(t){throw On()}mergeWith(t){return!1}integrate(t,i){}delete(t){}gc(t){}write(t,i){t.writeJSON(this.embed)}getRef(){return 5}}const XM=n=>new Mi(n.readJSON());class he{constructor(t,i){this.key=t,this.value=i}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new he(this.key,this.value)}splice(t){throw On()}mergeWith(t){return!1}integrate(t,i){const r=i.parent;r._searchMarker=null,r._hasFormatting=!0}delete(t){}gc(t){}write(t,i){t.writeKey(this.key),t.writeJSON(this.value)}getRef(){return 6}}const JM=n=>new he(n.readKey(),n.readJSON());class Ic{constructor(t){this.arr=t}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new Ic(this.arr)}splice(t){const i=new Ic(this.arr.slice(t));return this.arr=this.arr.slice(0,t),i}mergeWith(t){return this.arr=this.arr.concat(t.arr),!0}integrate(t,i){}delete(t){}gc(t){}write(t,i){const r=this.arr.length;t.writeLen(r-i);for(let l=i;l{const t=n.readLen(),i=[];for(let r=0;r{const t=n.readLen(),i=[];for(let r=0;r=55296&&r<=56319&&(this.str=this.str.slice(0,t-1)+`�`,i.str=`�`+i.str.slice(1)),i}mergeWith(t){return this.str+=t.str,!0}integrate(t,i){}delete(t){}gc(t){}write(t,i){t.writeString(i===0?this.str:this.str.slice(i))}getRef(){return 4}}const t2=n=>new Vn(n.readString()),e2=[kM,zM,IM,qM,HM,VM,$M],n2=0,s2=1,i2=2,r2=3,a2=4,l2=5,o2=6;class Ss{constructor(t){this.type=t}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new Ss(this.type._copy())}splice(t){throw On()}mergeWith(t){return!1}integrate(t,i){this.type._integrate(t.doc,i)}delete(t){let i=this.type._start;for(;i!==null;)i.deleted?i.id.clock<(t.beforeState.get(i.id.client)||0)&&t._mergeStructs.push(i):i.delete(t),i=i.right;this.type._map.forEach(r=>{r.deleted?r.id.clock<(t.beforeState.get(r.id.client)||0)&&t._mergeStructs.push(r):r.delete(t)}),t.changed.delete(this.type)}gc(t){let i=this.type._start;for(;i!==null;)i.gc(t,!0),i=i.right;this.type._start=null,this.type._map.forEach(r=>{for(;r!==null;)r.gc(t,!0),r=r.left}),this.type._map=new Map}write(t,i){this.type._write(t)}getRef(){return 7}}const c2=n=>new Ss(e2[n.readTypeRef()](n)),Hc=(n,t,i)=>{const{client:r,clock:l}=t.id,o=new fe(Rt(r,l+i),t,Rt(r,l+i-1),t.right,t.rightOrigin,t.parent,t.parentSub,t.content.splice(i));return t.deleted&&o.markDeleted(),t.keep&&(o.keep=!0),t.redone!==null&&(o.redone=Rt(t.redone.client,t.redone.clock+i)),t.right=o,o.right!==null&&(o.right.left=o),n._mergeStructs.push(o),o.parentSub!==null&&o.right===null&&o.parent._map.set(o.parentSub,o),t.length=i,o};class fe extends Kp{constructor(t,i,r,l,o,u,d,p){super(t,p.getLength()),this.origin=r,this.left=i,this.right=l,this.rightOrigin=o,this.parent=u,this.parentSub=d,this.redone=null,this.content=p,this.info=this.content.isCountable()?QS:0}set marker(t){(this.info&ed)>0!==t&&(this.info^=ed)}get marker(){return(this.info&ed)>0}get keep(){return(this.info&FS)>0}set keep(t){this.keep!==t&&(this.info^=FS)}get countable(){return(this.info&QS)>0}get deleted(){return(this.info&td)>0}set deleted(t){this.deleted!==t&&(this.info^=td)}markDeleted(){this.info|=td}getMissing(t,i){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=me(i,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=me(i,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===kr&&this.id.client!==this.parent.client&&this.parent.clock>=me(i,this.parent.client))return this.parent.client;if(this.origin&&(this.left=fv(t,i,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=Zs(t,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===vn||this.right&&this.right.constructor===vn)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===fe?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===fe&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===kr){const r=ld(i,this.parent);r.constructor===vn?this.parent=null:this.parent=r.content.type}return null}integrate(t,i){if(i>0&&(this.id.clock+=i,this.left=fv(t,t.doc.store,Rt(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(i),this.length-=i),this.parent){if(!this.left&&(!this.right||this.right.left!==null)||this.left&&this.left.right!==this.right){let r=this.left,l;if(r!==null)l=r.right;else if(this.parentSub!==null)for(l=this.parent._map.get(this.parentSub)||null;l!==null&&l.left!==null;)l=l.left;else l=this.parent._start;const o=new Set,u=new Set;for(;l!==null&&l!==this.right;){if(u.add(l),o.add(l),ec(this.origin,l.origin)){if(l.id.client{r.p===t&&(r.p=this,!this.deleted&&this.countable&&(r.index-=this.length))}),t.keep&&(this.keep=!0),this.right=t.right,this.right!==null&&(this.right.left=this),this.length+=t.length,!0}return!1}delete(t){if(!this.deleted){const i=this.parent;this.countable&&this.parentSub===null&&(i._length-=this.length),this.markDeleted(),Uc(t.deleteSet,this.id.client,this.id.clock,this.length),dv(t,i,this.parentSub),this.content.delete(t)}}gc(t,i){if(!this.deleted)throw bn();this.content.gc(t),i?gM(t,this,new vn(this.id,this.length)):this.content=new wl(this.length)}write(t,i){const r=i>0?Rt(this.id.client,this.id.clock+i-1):this.origin,l=this.rightOrigin,o=this.parentSub,u=this.content.getRef()&Qc|(r===null?0:rn)|(l===null?0:gs)|(o===null?0:hl);if(t.writeInfo(u),r!==null&&t.writeLeftID(r),l!==null&&t.writeRightID(l),r===null&&l===null){const d=this.parent;if(d._item!==void 0){const p=d._item;if(p===null){const g=dM(d);t.writeParentInfo(!0),t.writeString(g)}else t.writeParentInfo(!1),t.writeLeftID(p.id)}else d.constructor===String?(t.writeParentInfo(!0),t.writeString(d)):d.constructor===kr?(t.writeParentInfo(!1),t.writeLeftID(d)):bn();o!==null&&t.writeString(o)}this.content.write(t,i)}}const zw=(n,t)=>u2[t&Qc](n),u2=[()=>{bn()},FM,ZM,YM,t2,XM,JM,c2,PM,QM,()=>{bn()}],f2=10;class _n extends Kp{get deleted(){return!0}delete(){}mergeWith(t){return this.constructor!==t.constructor?!1:(this.length+=t.length,!0)}integrate(t,i){bn()}write(t,i){t.writeInfo(f2),Dt(t.restEncoder,this.length-i)}getMissing(t,i){return null}}const Nw=typeof globalThis<`u`?globalThis:typeof window<`u`?window:typeof global<`u`?global:{},jw=`__ $YJS$ __`;Nw[jw]===!0&&console.error(`Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438`);Nw[jw]=!0;const Bw=Math.floor,h2=(n,t)=>nn>t?n:t,Lw=128,mc=127,p2=Number.MAX_SAFE_INTEGER,Iw=()=>new Set,Hw=Array.from,g2=n=>{const t=unescape(encodeURIComponent(n)),i=t.length,r=new Uint8Array(i);for(let l=0;lEl.encode(n),m2=El?y2:g2;let il=typeof TextDecoder>`u`?null:new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0});il&&il.decode(new Uint8Array).length===1&&(il=null);class S2{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const qw=()=>new S2,v2=n=>{let t=n.cpos;for(let i=0;i{const t=new Uint8Array(v2(n));let i=0;for(let r=0;r{const i=n.cbuf.length;n.cpos===i&&(n.bufs.push(n.cbuf),n.cbuf=new Uint8Array(i*2),n.cpos=0),n.cbuf[n.cpos++]=t},zr=(n,t)=>{for(;t>mc;)qc(n,Lw|mc&t),t=Bw(t/128);qc(n,mc&t)},Fd=new Uint8Array(3e4),b2=Fd.length/3,w2=(n,t)=>{if(t.length{const i=unescape(encodeURIComponent(t)),r=i.length;zr(n,r);for(let l=0;l{const i=n.cbuf.length,r=n.cpos,l=h2(i-r,t.length),o=t.length-l;n.cbuf.set(t.subarray(0,l),r),n.cpos+=l,o>0&&(n.bufs.push(n.cbuf),n.cbuf=new Uint8Array(d2(i*2,o)),n.cbuf.set(t.subarray(l)),n.cpos=o)},Vw=(n,t)=>{zr(n,t.byteLength),x2(n,t)},$w=n=>new Error(n),_2=$w(`Unexpected end of array`),T2=$w(`Integer out of Range`);class A2{constructor(t){this.arr=t,this.pos=0}}const Qd=n=>new A2(n),vv=n=>n.pos!==n.arr.length,O2=(n,t)=>{const i=new Uint8Array(n.arr.buffer,n.pos+n.arr.byteOffset,t);return n.pos+=t,i},Xd=n=>O2(n,rl(n)),bv=n=>n.arr[n.pos++],rl=n=>{let t=0,i=1;const r=n.arr.length;for(;n.posp2)throw T2}throw _2},R2=n=>{let t=rl(n);if(t===0)return``;{let i=String.fromCodePoint(bv(n));if(--t<100)for(;t--;)i+=String.fromCodePoint(bv(n));else for(;t>0;){const r=t<1e4?t:1e4,l=n.arr.subarray(n.pos,n.pos+r);n.pos+=r,i+=String.fromCodePoint.apply(null,l),t-=r}return decodeURIComponent(escape(i))}},D2=n=>il.decode(Xd(n)),M2=il?D2:R2,Kc=Date.now,Nr=()=>new Map,Gw=(n,t,i)=>{let r=n.get(t);return r===void 0&&n.set(t,r=i()),r};class k2{constructor(){this._observers=Nr()}on(t,i){return Gw(this._observers,t,Iw).add(i),i}once(t,i){const r=(...l)=>{this.off(t,r),i(...l)};this.on(t,r)}off(t,i){const r=this._observers.get(t);r!==void 0&&(r.delete(i),r.size===0&&this._observers.delete(t))}emit(t,i){return Hw((this._observers.get(t)||Nr()).values()).forEach(r=>r(...i))}destroy(){this._observers=Nr()}}class U2{constructor(){this._observers=Nr()}on(t,i){Gw(this._observers,t,Iw).add(i)}once(t,i){const r=(...l)=>{this.off(t,r),i(...l)};this.on(t,r)}off(t,i){const r=this._observers.get(t);r!==void 0&&(r.delete(i),r.size===0&&this._observers.delete(t))}emit(t,i){return Hw((this._observers.get(t)||Nr()).values()).forEach(r=>r(...i))}destroy(){this._observers=Nr()}}const wv=Symbol(`Equality`),z2=Object.keys,Ev=n=>z2(n).length,N2=(n,t)=>Object.prototype.hasOwnProperty.call(n,t),al=(n,t)=>{if(n===t)return!0;if(n==null||t==null||n.constructor!==t.constructor&&(n.constructor||Object)!==(t.constructor||Object))return!1;if(n[wv]!=null)return n[wv](t);switch(n.constructor){case ArrayBuffer:n=new Uint8Array(n),t=new Uint8Array(t);case Uint8Array:{if(n.byteLength!==t.byteLength)return!1;for(let i=0;i{const i=Kc();this.getLocalState()!==null&&ud/2<=i-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());const r=[];this.meta.forEach((l,o)=>{o!==this.clientID&&ud<=i-l.lastUpdated&&this.states.has(o)&&r.push(o)}),r.length>0&&B2(this,r,`timeout`)},Bw(ud/10)),t.on(`destroy`,()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit(`destroy`,[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(t){const i=this.clientID,r=this.meta.get(i),l=r===void 0?0:r.clock+1,o=this.states.get(i);t===null?this.states.delete(i):this.states.set(i,t),this.meta.set(i,{clock:l,lastUpdated:Kc()});const u=[],d=[],p=[],g=[];t===null?g.push(i):o==null?t!=null&&u.push(i):(d.push(i),al(o,t)||p.push(i)),(u.length>0||p.length>0||g.length>0)&&this.emit(`change`,[{added:u,updated:p,removed:g},`local`]),this.emit(`update`,[{added:u,updated:d,removed:g},`local`])}setLocalStateField(t,i){const r=this.getLocalState();r!==null&&this.setLocalState({...r,[t]:i})}getStates(){return this.states}}const B2=(n,t,i)=>{const r=[];for(let l=0;l0&&(n.emit(`change`,[{added:[],updated:[],removed:r},i]),n.emit(`update`,[{added:[],updated:[],removed:r},i]))},Cv=(n,t,i=n.states)=>{const r=t.length,l=qw();zr(l,r);for(let o=0;o{const r=Qd(t),l=Kc(),o=[],u=[],d=[],p=[],g=rl(r);for(let y=0;y0||d.length>0||p.length>0)&&n.emit(`change`,[{added:o,updated:d,removed:p},i]),(o.length>0||u.length>0||p.length>0)&&n.emit(`update`,[{added:o,updated:u,removed:p},i])},I2={disconnected:[`connecting`],connecting:[`connected`,`disconnected`],connected:[`disconnected`]},H2=15e3;var q2=class Sc extends k2{doc;awareness;baseUrl;docId;headers;liveMode;_state=`disconnected`;_connectionId=0;_ctx=null;_synced=!1;updatesStreamGeneration=0;updatesSubscription=null;sendingAwareness=!1;pendingAwareness=null;awarenessHeartbeat=null;constructor(t){super(),this.doc=t.doc,this.awareness=t.awareness,this.baseUrl=t.baseUrl.replace(/\/$/,``),this.docId=t.docId,this.headers=t.headers??{},this.liveMode=t.liveMode??`sse`,this.doc.on(`update`,this.handleDocumentUpdate),this.awareness&&this.awareness.on(`update`,this.handleAwarenessUpdate),t.connect!==!1&&this.connect()}get synced(){return this._synced}set synced(t){this._synced!==t&&(this._synced=t,this.emit(`synced`,[t]))}get connected(){return this._state===`connected`}get connecting(){return this._state===`connecting`}transition(t){return I2[this._state].includes(t)?(this._state=t,this.emit(`status`,[t]),!0):(console.warn(`[YjsProvider] Invalid transition: ${this._state} -> ${t}`),!1)}createConnectionContext(){this._connectionId+=1;const t={id:this._connectionId,controller:new AbortController,startOffset:`-1`,producer:null};return this._ctx=t,t}isStale(t){return this._ctx!==t||t.controller.signal.aborted}async connect(){if(this._state!==`disconnected`||!this.transition(`connecting`))return;const t=this.createConnectionContext();try{if(await this.ensureDocument(t),this.isStale(t)||(await this.discoverSnapshot(t),this.isStale(t))||(this.createUpdatesProducer(t),await this.startUpdatesStream(t,t.startOffset),this.isStale(t)))return;this.awareness&&this.startAwareness(t)}catch(i){!(i instanceof Error&&i.name===`AbortError`)&&!this.isStale(t)&&(this.emit(`error`,[i instanceof Error?i:new Error(String(i))]),this.disconnect())}}async disconnect(){const t=this._ctx;!t||this._state===`disconnected`||(this.transition(`disconnected`),this._ctx=null,this.synced=!1,this.awarenessHeartbeat&&(clearInterval(this.awarenessHeartbeat),this.awarenessHeartbeat=null),this.awareness&&this.broadcastAwarenessRemoval(),this.updatesStreamGeneration+=1,this.updatesSubscription&&(this.updatesSubscription(),this.updatesSubscription=null),await this.closeUpdatesProducer(t),t.controller.abort(),this.pendingAwareness=null)}destroy(){this.disconnect().catch(()=>{}),this.doc.off(`update`,this.handleDocumentUpdate),this.awareness&&this.awareness.off(`update`,this.handleAwarenessUpdate),super.destroy()}async flush(){this._ctx?.producer&&await this._ctx.producer.flush()}docUrl(){return`${this.baseUrl}/docs/${this.docId}`}awarenessUrl(t=`default`){return`${this.docUrl()}?awareness=${encodeURIComponent(t)}`}async ensureDocument(t){const i=this.docUrl(),r=await fetch(i,{method:`PUT`,headers:{...this.headers,"content-type":`application/octet-stream`},signal:t.controller.signal});if(r.status===201||r.status===200){await r.arrayBuffer();return}if(r.status===409){await r.arrayBuffer();return}const l=await r.text().catch(()=>``);throw new Error(`Failed to create document: ${r.status} ${l}`)}async discoverSnapshot(t){const i=`${this.docUrl()}?offset=snapshot`,r=await fetch(i,{method:`GET`,headers:this.headers,redirect:`manual`,signal:t.controller.signal});if(r.status===307){const l=r.headers.get(`location`);if(l){const u=new URL(l,i).searchParams.get(`offset`);if(u){u.endsWith(`_snapshot`)?await this.loadSnapshot(t,u):t.startOffset=u;return}}}t.startOffset=`-1`}async loadSnapshot(t,i){const r=`${this.docUrl()}?offset=${encodeURIComponent(i)}`;try{const l=await fetch(r,{method:`GET`,headers:this.headers,signal:t.controller.signal});if(!l.ok){if(l.status===404){await this.discoverSnapshot(t);return}throw new Error(`Failed to load snapshot: ${l.status}`)}const o=new Uint8Array(await l.arrayBuffer());o.length>0&&lv(this.doc,o,`server`);const u=l.headers.get(`stream-next-offset`);t.startOffset=u??`-1`}catch(l){if(this.isNotFoundError(l)){await this.discoverSnapshot(t);return}throw l}}createUpdatesProducer(t){const i=new Ys({url:this.docUrl(),headers:this.headers,contentType:`application/octet-stream`}),r=`${this.docId}-${this.doc.clientID}`;t.producer=new wb(i,r,{autoClaim:!0,signal:t.controller.signal,onError:l=>{l instanceof Error&&l.name===`AbortError`||(console.error(`[YjsProvider] Producer error:`,l),this.emit(`error`,[l]),this.isAuthError(l)||(this.disconnect(),this.connect()))}})}async closeUpdatesProducer(t){if(t.producer){try{await t.producer.close()}catch{}t.producer=null}}startUpdatesStream(t,i){if(t.controller.signal.aborted)return Promise.resolve();this.updatesStreamGeneration+=1;const r=this.updatesStreamGeneration;this.updatesSubscription?.(),this.updatesSubscription=null;let l=!1,o,u;const d=new Promise((p,g)=>{o=()=>{l||(l=!0,p())},u=y=>{l||(l=!0,g(y))}});return this.runUpdatesStream(t,i,r,o,u).catch(p=>{u(p instanceof Error?p:new Error(String(p)))}),d}async runUpdatesStream(t,i,r,l,o){let u=i,d=!0;const p=()=>{d&&(d=!1,this._state===`connecting`&&this.transition(`connected`),this.synced=!0,l())},g=()=>this.isStale(t)||this.updatesStreamGeneration!==r;for(;this.updatesStreamGeneration===r;){if(t.controller.signal.aborted){p();return}const y=new Ys({url:this.docUrl(),headers:this.headers,contentType:`application/octet-stream`});try{const m=await y.stream({offset:u,live:this.liveMode,signal:t.controller.signal});this.updatesSubscription?.(),this.updatesSubscription=m.subscribeBytes(async v=>{g()||(u=v.offset,v.data.length>0&&this.applyUpdates(v.data),d&&v.upToDate?p():v.data.length>0&&(this.synced=!0))}),await m.closed,p();continue}catch(m){if(g()){p();return}if(this.isNotFoundError(m)){if(d){o(m instanceof Error?m:new Error(String(m)));return}this.emit(`error`,[m instanceof Error?m:new Error(String(m))]),this.disconnect();return}if(d){o(m instanceof Error?m:new Error(String(m)));return}await new Promise(v=>setTimeout(v,1e3))}finally{this.updatesSubscription&&(this.updatesSubscription(),this.updatesSubscription=null)}}}static frameUpdate(t){const i=qw();return Vw(i,t),Kw(i)}applyUpdates(t){if(t.length===0)return;const i=Qd(t);for(;vv(i);){const r=Xd(i);lv(this.doc,r,`server`)}}applyAwarenessUpdates(t){if(!(t.length===0||!this.awareness))try{const i=Qd(t);for(;vv(i);){const r=Xd(i);try{L2(this.awareness,r,`server`)}catch{}}}catch{}}handleDocumentUpdate=(t,i)=>{if(i===`server`)return;const r=this._ctx?.producer;!r||!this.connected||(this.synced=!1,r.append(Sc.frameUpdate(t)))};startAwareness(t){this.awareness&&(t.controller.signal.aborted||(this.broadcastAwareness(),this.awarenessHeartbeat=setInterval(()=>{this.broadcastAwareness()},H2),this.subscribeAwareness(t)))}handleAwarenessUpdate=(t,i)=>{if(!this.awareness||i===`server`||i===this)return;const{added:r,updated:l,removed:o}=t;r.concat(l).concat(o).includes(this.awareness.clientID)&&(this.pendingAwareness=t,this.sendAwareness())};broadcastAwareness(){this.awareness&&(this.pendingAwareness={added:[this.awareness.clientID],updated:[],removed:[]},this.sendAwareness())}broadcastAwarenessRemoval(){if(this.awareness)try{this.awareness.setLocalState(null);const t=Cv(this.awareness,[this.awareness.clientID]);new Ys({url:this.awarenessUrl(),headers:this.headers,contentType:`application/octet-stream`}).append(Sc.frameUpdate(t),{contentType:`application/octet-stream`}).catch(()=>{})}catch{}}async sendAwareness(){if(!(!this.awareness||!this.connected&&!this.connecting||this.sendingAwareness)){this.sendingAwareness=!0;try{for(;this.pendingAwareness;){const t=this.pendingAwareness;this.pendingAwareness=null;const{added:i,updated:r,removed:l}=t,o=i.concat(r).concat(l),u=Cv(this.awareness,o);await new Ys({url:this.awarenessUrl(),headers:this.headers,contentType:`application/octet-stream`}).append(Sc.frameUpdate(u),{contentType:`application/octet-stream`})}}catch(t){console.error(`[YjsProvider] Failed to send awareness:`,t)}finally{this.sendingAwareness=!1}}}async subscribeAwareness(t){if(!this.awareness)return;const i=t.controller.signal;if(i.aborted)return;const r=new Ys({url:this.awarenessUrl(),headers:this.headers,contentType:`application/octet-stream`});try{const l=await r.stream({offset:`now`,live:`sse`,signal:i});l.closed.catch(()=>{}),l.subscribeBytes(async o=>{i.aborted||o.data.length>0&&this.applyAwarenessUpdates(o.data)}),await l.closed,this.connected&&!i.aborted&&(await new Promise(o=>setTimeout(o,250)),this.subscribeAwareness(t))}catch(l){if(i.aborted||!this.connected&&!this.connecting)return;if(this.isNotFoundError(l)){console.error(`[YjsProvider] Awareness stream not found`);return}console.error(`[YjsProvider] Awareness stream error:`,l),await new Promise(o=>setTimeout(o,1e3)),this.connected&&this.subscribeAwareness(t)}}isNotFoundError(t){return t instanceof Wt&&t.code===`NOT_FOUND`||t instanceof Js&&t.status===404}isAuthError(t){return t instanceof Wt&&(t.code===`UNAUTHORIZED`||t.code===`FORBIDDEN`)||t instanceof Js&&(t.status===401||t.status===403)}};const K2=64,V2=64,xv=200,$2=1500,vc=.3,_v=12e4,G2=`#d0bcff`,ic=[`#FF0055`,`#00FF88`,`#FFEE00`,`#00CCFF`,`#FF6600`,`#00FFCC`,`#FF2299`,`#33FF00`,`#FF00AA`,`#00AAFF`,`#FFAA00`,`#CC00FF`,`#00FF55`,`#FF4400`,`#0066FF`];function Y2(n){const t=n.match(/__(\d+)x(\d+)(?:_(\d+)ms)?$/);return t?{cols:parseInt(t[1]),rows:parseInt(t[2])}:{cols:K2,rows:V2}}function ll(n){return n.getMap(`territoryCell`)}function jn(n){return n.getMap(`players`)}function cu(n){return n.getMap(`gameState`)}function Yw(n,t){const i=jn(n),r=new Map;return i.forEach((l,o)=>{o!==t&&r.set(o,l)}),r}function fd(n){const t=ll(n),i=new Map;return t.forEach((r,l)=>{i.set(l,r)}),i}function F2(n,t){let i=0;return n.forEach(r=>{r.owner===t&&i++}),i}function Q2(n,t,i,r){const l=new Set;t.forEach((p,g)=>{p.owner===n&&l.add(g)});const o=new Set,u=[];for(let p=0;p0;){const{x:p,y:g}=u.pop();for(const[y,m]of[[0,-1],[0,1],[-1,0],[1,0]]){const v=p+y,w=g+m;if(v<0||v>=i||w<0||w>=r)continue;const b=`${v},${w}`;l.has(b)||o.has(b)||(o.add(b),u.push({x:v,y:w}))}}const d=[];for(let p=0;pA.x===m&&A.y===v);if(b){const[A,M]=b,G=p+$2,q=jn(n);return q.set(A,{...M,stunnedUntil:G}),q.set(t,{x:r.x,y:r.y,name:i,stunnedUntil:G}),{moved:!1,stunned:!0,x:r.x,y:r.y,stunnedUntil:G}}jn(n).set(t,{x:m,y:v,name:i});const _=ll(n),j=Date.now();n.transact(()=>{_.set(`${m},${v}`,{owner:t,claimedAt:j})});const O=Q2(t,_,o,u);return O.length>0&&n.transact(()=>{for(const A of O)_.set(`${A.x},${A.y}`,{owner:t,claimedAt:j})}),{moved:!0,stunned:!1,x:m,y:v,stunnedUntil:0}}function Tv(n){const t=cu(n);t.has(`gameStartedAt`)||n.transact(()=>{t.has(`gameStartedAt`)||t.set(`gameStartedAt`,Date.now())})}function Z2(n){const i=cu(n).get(`gameStartedAt`);return i!==void 0?i:null}function hd(n){const i=cu(n).get(`gameEndedAt`);return i!==void 0?i:null}function Av(n){const t=cu(n);(!t.has(`gameEndedAt`)||t.get(`gameEndedAt`)===null)&&n.transact(()=>{t.set(`gameEndedAt`,Date.now())})}function Vp(n){const t=new Map;return n.forEach(i=>{t.set(i.owner,(t.get(i.owner)||0)+1)}),t}function Ov(n,t,i){const r=Vp(n),l=vc*t;for(const[o,u]of r)if(u>=l){const d=i.get(o);if(d)return{name:d.name,pct:Math.round(u/t*100)}}return null}function Rv(n,t,i){const r=Vp(n);let l=0,o=``;if(r.forEach((d,p)=>{d>l&&(l=d,o=p)}),!o||l===0)return null;const u=i.get(o);return u?{name:u.name,pct:Math.round(l/t*100)}:null}const Fw=J.createContext(null);function W2(){const n=J.useContext(Fw);if(!n)throw new Error(`useGameRoom must be used within GameRoom`);return n}function P2(n,t){return{streamOptions:{url:n,headers:t,contentType:`application/json`},state:GS,actions:({db:i,stream:r})=>({submitScore:{onMutate:l=>{i.collections.scores.insert(l)},mutationFn:async l=>{const o=crypto.randomUUID();await r.append(JSON.stringify(GS.scores.insert({value:l,headers:{txid:o}}))),await i.utils.awaitTxId(o)}}})}}function tk(n,t){return _b(P2(n,t))}const ek=J.createContext(null);function nk({roomId:n,children:t}){const{dsEndpoint:i,dsHeaders:r}=Zd(),{db:l,error:o}=tk(`${i}/__snake_scores_${encodeURIComponent(n)}`,r);return o&&console.warn(`[Scores] Error loading scores:`,o.message),F.jsx(ek.Provider,{value:l?{scoresDB:l}:null,children:t})}const sk=1,br=8,Dv=14,Vt={bg:`#1b1b1f`,grid:`#202127`,gridLine:`#2e2e32`,border:`#2e2e32`,text:`rgba(235,235,245,0.68)`,accent:`#d0bcff`,dim:`rgba(235,235,245,0.38)`},wr={ArrowUp:{dx:0,dy:-1},ArrowDown:{dx:0,dy:1},ArrowLeft:{dx:-1,dy:0},ArrowRight:{dx:1,dy:0},w:{dx:0,dy:-1},s:{dx:0,dy:1},a:{dx:-1,dy:0},d:{dx:1,dy:0}};function ik(n,t){return n>256||t>256?2:n>64||t>64?4:14}function rk({onLeave:n}){const{doc:t,awareness:i,roomId:r,playerId:l,playerName:o,playerColor:u}=W2(),{cols:d,rows:p}=J.useMemo(()=>Y2(r),[r]),g=d*p,y=J.useMemo(()=>ik(d,p),[d,p]),m=d<=100&&p<=100,[v,w]=J.useState(new Map),[b,E]=J.useState(new Map),[_,j]=J.useState({x:0,y:0}),[O,A]=J.useState(1),[M,G]=J.useState(!1),[q,K]=J.useState(!1),[W,et]=J.useState(null),[X,at]=J.useState(_v/1e3),nt=r.replace(/__\d+x\d+(?:_\d+ms)?$/,``),bt=J.useRef(void 0),Lt=J.useRef(null),dt=J.useRef({x:0,y:0,stunnedUntil:0}),k=J.useMemo(()=>F2(v,l)*sk,[v,l]),I=J.useMemo(()=>Math.round(k/g*100),[k,g]),Z=J.useMemo(()=>Vp(v),[v]),it=J.useRef(null),[ft,T]=J.useState(!1),B=J.useMemo(()=>{let tt=0,P=``;if(Z.forEach((ht,Qt)=>{ht>tt&&(tt=ht,P=Qt)}),!P||tt===0)return null;const gt=Math.round(tt/g*100);if(P===l)return{name:o,pct:gt};const pt=b.get(P);return pt?{name:pt.name,pct:gt}:null},[Z,g,l,o,b]);J.useEffect(()=>{if(B){if(it.current!==null&&it.current!==B.name){T(!0);const tt=setTimeout(()=>T(!1),900);return()=>clearTimeout(tt)}it.current=B.name}},[B]),J.useEffect(()=>{const tt=Math.floor(Math.random()*d),P=Math.floor(Math.random()*p);dt.current={x:tt,y:P,stunnedUntil:0},j({x:tt,y:P});const gt=jn(t);gt.set(l,{x:tt,y:P,name:o});const pt=ll(t);return t.transact(()=>{pt.set(`${tt},${P}`,{owner:l,claimedAt:Date.now()})}),Tv(t),()=>{gt.delete(l)}},[t,l,o,u,d,p]),J.useEffect(()=>{const tt=ll(t),P=()=>{const gt=fd(t);if(w(gt),hd(t)!==null)return;const pt=Ov(gt,g,jn(t));pt&&(et(pt),Av(t))};return tt.observe(P),P(),()=>tt.unobserve(P)},[t,g]),J.useEffect(()=>{const tt=()=>{const gt=Z2(t);if(!gt)return;const pt=Date.now()-gt,ht=Math.max(0,_v-pt);at(Math.ceil(ht/1e3));const Qt=hd(t)!==null;if(ht<=0&&!Qt){const De=fd(t),Ge=Rv(De,g,jn(t));et(Ge||{name:`Nobody`,pct:0}),Av(t)}else Qt&&et(De=>{if(De)return De;const Ge=fd(t),Ye=Ov(Ge,g,jn(t));return Ye||(Rv(Ge,g,jn(t))??{name:`Nobody`,pct:0})})},P=setInterval(tt,1e3);return tt(),()=>clearInterval(P)},[t,g]),J.useEffect(()=>{const tt=jn(t),P=()=>{E(Yw(t,l))};return tt.observe(P),P(),()=>tt.unobserve(P)},[t,l]),J.useEffect(()=>{const tt=()=>{const P=new Set,gt=new Set([o]);i.getStates().forEach((ht,Qt)=>{if(Qt!==i.clientID){ht.playerId&&P.add(ht.playerId);const De=ht.user?.name;De&>.add(De)}}),A(ht=>{const Qt=gt.size;return ht===Qt?ht:Qt});const pt=jn(t);pt.forEach((ht,Qt)=>{Qt!==l&&!P.has(Qt)&&pt.delete(Qt)})};return i.on(`change`,tt),tt(),()=>i.off(`change`,tt)},[i,t,l,o]),J.useEffect(()=>{const tt=new Set,P=pt=>{if(pt.key in wr){pt.preventDefault();const ht=!Lt.current;tt.add(pt.key),Lt.current=wr[pt.key],ht&&$e.current?.(wr[pt.key])}},gt=pt=>{if(tt.delete(pt.key),pt.key in wr){let ht=!1;for(const Qt of tt)if(Qt in wr){Lt.current=wr[Qt],ht=!0;break}ht||(Lt.current=null)}};return window.addEventListener(`keydown`,P),window.addEventListener(`keyup`,gt),()=>{window.removeEventListener(`keydown`,P),window.removeEventListener(`keyup`,gt)}},[]);const Y=J.useRef(null),Q=J.useRef(null),ot=J.useRef(0),st=10,mt=J.useCallback((tt,P)=>{const gt=Date.now();if(gt-ot.currentMath.abs(Wr)?$e.current?.({dx:zi>0?1:-1,dy:0}):$e.current?.({dx:0,dy:Wr>0?1:-1}),ot.current=gt)},[y]),Ut=J.useCallback(tt=>{tt.preventDefault();const P=tt.touches[0];Q.current={x:P.clientX,y:P.clientY},mt(P.clientX,P.clientY)},[mt]),wt=J.useCallback(tt=>{if(tt.preventDefault(),!Q.current)return;const P=tt.touches[0],gt=P.clientX-Q.current.x,pt=P.clientY-Q.current.y;Math.abs(gt){Q.current=null},[]),$e=J.useRef(void 0),Ps=J.useCallback(tt=>{const P=Y.current;if(!P)return;const gt=P.createSVGPoint();gt.x=tt.clientX,gt.y=tt.clientY;const pt=P.getScreenCTM();if(!pt)return;const ht=gt.matrixTransform(pt.inverse()),Qt=ht.x/y-.5,De=ht.y/y-.5,Ge=dt.current,Ye=Qt-Ge.x,Gn=De-Ge.y;Ye===0&&Gn===0||(Math.abs(Ye)>Math.abs(Gn)?$e.current?.({dx:Ye>0?1:-1,dy:0}):$e.current?.({dx:0,dy:Gn>0?1:-1}))},[y]),ki=J.useCallback(()=>{n()},[n]);J.useEffect(()=>{const tt=gt=>{if(hd(t)!==null)return;const pt=dt.current,ht=J2(t,l,o,{x:pt.x,y:pt.y},gt,d,p,pt.stunnedUntil);pt.stunnedUntil=ht.stunnedUntil,ht.moved&&(pt.x=ht.x,pt.y=ht.y,j({x:ht.x,y:ht.y}),i.setLocalState({...i.getLocalState(),x:ht.x,y:ht.y}))};$e.current=tt;const P=setInterval(()=>{const gt=Lt.current;gt&&tt(gt)},xv);return()=>clearInterval(P)},[t,l,o,u,d,p,i]);const Te=d*y,ti=p*y,Jr=J.useCallback(()=>{navigator.clipboard.writeText(nt).catch(()=>{}),G(!0),clearTimeout(bt.current),bt.current=setTimeout(()=>G(!1),1200)},[nt]);J.useEffect(()=>()=>clearTimeout(bt.current),[]);const uu=J.useMemo(()=>m?F.jsxs(F.Fragment,{children:[Array.from({length:d},(tt,P)=>F.jsx(`line`,{x1:P*y,y1:0,x2:P*y,y2:ti,stroke:Vt.gridLine,strokeWidth:.5},`v${P}`)),Array.from({length:p},(tt,P)=>F.jsx(`line`,{x1:0,y1:P*y,x2:Te,y2:P*y,stroke:Vt.gridLine,strokeWidth:.5},`h${P}`))]}):null,[d,p,Te,ti,y,m]),Ui=J.useMemo(()=>{const tt=new Map;tt.set(l,u);const P=[...b.keys()].sort();for(let gt=0;gt{const P=Math.floor(tt/60),gt=tt%60;return`${P}:${gt.toString().padStart(2,`0`)}`};return F.jsxs(`div`,{style:{display:`flex`,flexDirection:`column`,alignItems:`center`,fontFamily:`'Press Start 2P', monospace`,background:Vt.bg,color:Vt.text,minHeight:`100dvh`,maxHeight:`100dvh`,padding:8,boxSizing:`border-box`,overflow:`hidden`,touchAction:`none`},children:[F.jsx(`style`,{children:` + @import url('https://fonts.googleapis.com/css2?family=Press+Start+2P&display=swap'); + @keyframes blink { 0%,100% { opacity:1 } 50% { opacity:0.3 } } + .live-dot { animation: blink 1.5s ease-in-out infinite; } + @keyframes stun-pulse { 0%,100% { opacity:1 } 50% { opacity:0.2 } } + .stunned { animation: stun-pulse 0.3s ease-in-out infinite; } + @keyframes leader-blink { 0%,100% { opacity:1 } 50% { opacity:0 } } + .leader-blink { animation: leader-blink 0.3s ease-in-out 3; } + `}),F.jsxs(`div`,{style:{display:`flex`,alignItems:`center`,justifyContent:`space-between`,width:`100%`,maxWidth:Te,marginBottom:8,fontSize:br},children:[F.jsx(`button`,{onClick:ki,style:{background:`none`,border:`none`,color:Vt.accent,fontFamily:`inherit`,fontSize:br,padding:`4px 0`,cursor:`pointer`},children:`EXIT`}),F.jsxs(`div`,{style:{display:`flex`,gap:6,cursor:`pointer`},onClick:Jr,title:`Click to copy room name`,children:[F.jsx(`span`,{style:{color:Vt.accent},children:o}),F.jsx(`span`,{style:{color:Vt.dim},children:`@`}),F.jsx(`span`,{style:{color:M?Vt.accent:Vt.text,textDecoration:`underline`,textUnderlineOffset:3},children:M?`COPIED`:nt})]}),F.jsx(`span`,{style:{color:X<=30?`#FF3D71`:Vt.accent,fontVariantNumeric:`tabular-nums`},children:Zr(X)}),F.jsxs(`div`,{style:{color:Vt.accent,position:`relative`,cursor:`pointer`},onMouseEnter:()=>K(!0),onMouseLeave:()=>K(!1),onClick:()=>K(tt=>!tt),children:[O,` PLAYERS`,q&&F.jsx(`div`,{style:{position:`absolute`,top:`100%`,right:0,marginTop:6,background:Vt.bg,border:`1px solid ${Vt.border}`,padding:10,zIndex:5,minWidth:120},children:[{id:l,name:o},...Array.from(b.entries()).map(([tt,P])=>({id:tt,name:P.name}))].map(tt=>{const P=Ui.get(tt.id)??ic[0],gt=Z.get(tt.id)||0,pt=Math.round(gt/g*100);return F.jsxs(`div`,{style:{display:`flex`,justifyContent:`space-between`,gap:8,padding:`3px 0`},children:[F.jsxs(`span`,{style:{display:`flex`,alignItems:`center`,gap:4},children:[F.jsx(`span`,{style:{width:6,height:6,borderRadius:`50%`,background:P,display:`inline-block`}}),tt.name]}),F.jsxs(`span`,{style:{color:Vt.accent},children:[pt,`%`]})]},tt.id)})})]})]}),F.jsxs(`div`,{style:{display:`flex`,justifyContent:`space-between`,alignItems:`flex-end`,width:`100%`,maxWidth:Te,marginBottom:8,fontSize:br},children:[F.jsxs(`div`,{children:[F.jsxs(`span`,{style:{fontSize:Dv,color:Vt.accent},children:[I,`%`]}),` `,F.jsx(`span`,{style:{color:Vt.dim},children:`TERRITORY`})]}),F.jsxs(`div`,{style:{textAlign:`right`},children:[F.jsxs(`div`,{style:{marginBottom:B?4:0,color:B&&B.pct>=Math.round(vc*100)-5?`#FF3D71`:Vt.dim},children:[`WIN AT `,Math.round(vc*100),`%`]}),B&&F.jsxs(`div`,{children:[F.jsx(`span`,{className:ft?`leader-blink`:void 0,style:{color:Vt.dim},children:B.name}),` `,F.jsxs(`span`,{style:{fontSize:Dv,color:Vt.accent},children:[B.pct,`%`]})]})]})]}),F.jsxs(`svg`,{ref:Y,viewBox:`0 0 ${Te} ${ti}`,onTouchStart:Ut,onTouchMove:wt,onTouchEnd:an,onClick:Ps,style:{width:`min(100%, calc(100dvh - 140px))`,maxWidth:Te,height:`auto`,aspectRatio:`${d} / ${p}`,background:Vt.grid,border:`1px solid ${Vt.border}`,flexShrink:0,userSelect:`none`,WebkitUserSelect:`none`},children:[uu,Array.from(v.entries()).map(([tt,P])=>{const[gt,pt]=tt.split(`,`).map(Number),ht=Ui.get(P.owner)||Vt.accent;return F.jsx(`rect`,{x:gt*y,y:pt*y,width:y,height:y,fill:ht,opacity:.5},tt)}),Array.from(b.entries()).map(([tt,P])=>{const gt=P.stunnedUntil!=null&&Date.now(){const tt=dt.current.stunnedUntil>0&&Date.now(){const tt=ll(t),P=t.getMap(`gameState`);t.transact(()=>{Array.from(tt.keys()).forEach(pt=>tt.delete(pt)),P.delete(`gameStartedAt`),P.delete(`gameEndedAt`)}),et(null),Tv(t)},style:{fontFamily:`inherit`,fontSize:br,padding:`10px 24px`,background:Vt.accent,color:`#000`,border:`none`,cursor:`pointer`,letterSpacing:2},children:`REMATCH`}),F.jsx(`button`,{onClick:ki,style:{fontFamily:`inherit`,fontSize:br,padding:`10px 24px`,background:`transparent`,color:Vt.accent,border:`1px solid ${Vt.accent}`,cursor:`pointer`,letterSpacing:2},children:`EXIT`})]})]})]})}function ak({roomId:n,yjsBaseUrl:t,yjsHeaders:i,playerName:r,onLeave:l}){const{registryDB:o}=Ab(),[{playerId:u,doc:d,awareness:p}]=J.useState(()=>{const O=`player-${Math.random().toString(36).slice(2,10)}`,A=new Qr,M=new j2(A);return M.setLocalState({user:{name:r},playerId:O,type:`human`}),{playerId:O,doc:A,awareness:M}}),g=G2,[y,m]=J.useState(!0),[v,w]=J.useState(!1),[b,E]=J.useState(null),_=J.useRef(null);J.useEffect(()=>{const O=new q2({doc:d,baseUrl:t,docId:n,awareness:p,headers:i,connect:!1});return O.on(`synced`,A=>{w(A),A&&m(!1)}),O.on(`status`,A=>{A===`connected`&&m(!1)}),O.on(`error`,A=>{E(A),m(!1)}),p.getLocalState()===null&&p.setLocalState({user:{name:r},playerId:u,type:`human`}),_.current=O,O.connect(),()=>{O.destroy(),_.current=null}},[n,d,p,t,i,r,u]),J.useEffect(()=>{const A=setInterval(()=>{const M=new Set([u]);if(p.getStates().forEach(K=>{K.playerId&&M.add(K.playerId)}),[...M].sort()[0]!==u)return;const q=o.collections.rooms.toArray.find(K=>K.roomId===n);if(q)try{o.actions.addRoom({...q,expiresAt:Date.now()+bp*1e3})}catch{}},QO);return()=>clearInterval(A)},[p,o,n,u]),J.useEffect(()=>()=>{d.destroy()},[d]);const j=J.useMemo(()=>({doc:d,awareness:p,roomId:n,playerId:u,playerName:r,playerColor:g,isSynced:v,isLoading:y}),[d,p,n,u,r,g,v,y]);return b?F.jsxs(`div`,{style:dd.center,children:[F.jsxs(`div`,{style:{color:`#FF3D71`,fontSize:8},children:[`Connection error: `,b.message]}),F.jsx(`button`,{onClick:l,style:dd.btn,children:`BACK`})]}):y?F.jsxs(`div`,{style:dd.center,children:[F.jsx(`style`,{children:`@import url('https://fonts.googleapis.com/css2?family=Press+Start+2P&display=swap');`}),F.jsx(`div`,{style:{color:`#d0bcff`,fontSize:8},children:`CONNECTING...`})]}):F.jsx(Fw.Provider,{value:j,children:F.jsx(nk,{roomId:n,children:F.jsx(rk,{onLeave:l})})})}const dd={center:{display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,height:`100vh`,gap:16,fontFamily:`'Press Start 2P', monospace`,background:`#1b1b1f`},btn:{fontFamily:`inherit`,fontSize:8,padding:`8px 24px`,background:`#d0bcff`,color:`#000`,border:`none`,cursor:`pointer`}},Mv=[`Swift`,`Bold`,`Sly`,`Keen`,`Cool`,`Neon`,`Rad`,`Zen`],kv=[`Fox`,`Wolf`,`Hawk`,`Bear`,`Lynx`,`Crow`,`Stag`,`Hare`];function lk(){const n=Mv[Math.floor(Math.random()*Mv.length)],t=kv[Math.floor(Math.random()*kv.length)];return`${n} ${t}`}function ok(){return localStorage.getItem(`territory-player-name`)||lk()}function ck(){const[n,t]=J.useState(()=>{const i=window.location.hash.match(/^#room\/(.+)$/);return i?decodeURIComponent(i[1]):null});return J.useEffect(()=>{const i=()=>{const r=window.location.hash.match(/^#room\/(.+)$/);t(r?decodeURIComponent(r[1]):null)};return window.addEventListener(`hashchange`,i),()=>window.removeEventListener(`hashchange`,i)},[]),n}function uk(){const n=ck(),{yjsEndpoint:t,yjsHeaders:i}=Zd(),[r,l]=J.useState(ok),o=u=>{l(u),localStorage.setItem(`territory-player-name`,u)};return n?F.jsx(ak,{roomId:n,yjsBaseUrl:t,yjsHeaders:i,playerName:r,onLeave:()=>{window.location.hash=``}}):F.jsx(sR,{playerName:r,onPlayerNameChange:o,onJoinRoom:u=>{window.location.hash=`room/${encodeURIComponent(u)}`}})}function fk(){return F.jsx(CC,{children:F.jsx(tR,{children:F.jsx(uk,{})})})}wC.createRoot(document.getElementById(`root`)).render(F.jsx(fk,{})); diff --git a/website/public/demos/territory-wars/index.html b/website/public/demos/territory-wars/index.html new file mode 100644 index 0000000000..9402e5c83c --- /dev/null +++ b/website/public/demos/territory-wars/index.html @@ -0,0 +1,24 @@ + + + + + + Territory Wars - Multiplayer with Durable Streams + + + + +
+ + diff --git a/website/public/img/blog/yjs-durable-streams-on-electric-cloud/header.jpg b/website/public/img/blog/yjs-durable-streams-on-electric-cloud/header.jpg new file mode 100644 index 0000000000..559d93611f Binary files /dev/null and b/website/public/img/blog/yjs-durable-streams-on-electric-cloud/header.jpg differ diff --git a/website/public/img/blog/yjs-durable-streams-on-electric-cloud/header.png b/website/public/img/blog/yjs-durable-streams-on-electric-cloud/header.png new file mode 100644 index 0000000000..fe43803818 Binary files /dev/null and b/website/public/img/blog/yjs-durable-streams-on-electric-cloud/header.png differ diff --git a/website/public/img/demos/territory-wars-screenshot.png b/website/public/img/demos/territory-wars-screenshot.png new file mode 100644 index 0000000000..6d68ed0182 Binary files /dev/null and b/website/public/img/demos/territory-wars-screenshot.png differ diff --git a/website/src/components/SnapshotSyncDiagram.vue b/website/src/components/SnapshotSyncDiagram.vue new file mode 100644 index 0000000000..03c7f5c581 --- /dev/null +++ b/website/src/components/SnapshotSyncDiagram.vue @@ -0,0 +1,367 @@ + + +