diff --git a/src/Components/Components/src/IPersistentComponentStateStore.cs b/src/Components/Components/src/IPersistentComponentStateStore.cs index 1b14bca2a3ee..cd4c63ddbdf7 100644 --- a/src/Components/Components/src/IPersistentComponentStateStore.cs +++ b/src/Components/Components/src/IPersistentComponentStateStore.cs @@ -20,4 +20,11 @@ public interface IPersistentComponentStateStore /// The serialized state to persist. /// A that completes when the state is persisted to disk. Task PersistStateAsync(IReadOnlyDictionary state); + + /// + /// Returns a value that indicates whether the store supports the given . + /// + /// The in question. + /// true if the render mode is supported by the store, otherwise false. + bool SupportsRenderMode(IComponentRenderMode renderMode) => true; } diff --git a/src/Components/Components/src/Infrastructure/ComponentStatePersistenceManager.cs b/src/Components/Components/src/Infrastructure/ComponentStatePersistenceManager.cs index 6886ea4a4bce..e1b4fdf605ec 100644 --- a/src/Components/Components/src/Infrastructure/ComponentStatePersistenceManager.cs +++ b/src/Components/Components/src/Infrastructure/ComponentStatePersistenceManager.cs @@ -11,17 +11,18 @@ namespace Microsoft.AspNetCore.Components.Infrastructure; /// public class ComponentStatePersistenceManager { + private readonly List _registeredCallbacks = new(); + private readonly ILogger _logger; + private bool _stateIsPersisted; - private readonly List> _pauseCallbacks = new(); private readonly Dictionary _currentState = new(StringComparer.Ordinal); - private readonly ILogger _logger; /// /// Initializes a new instance of . /// public ComponentStatePersistenceManager(ILogger logger) { - State = new PersistentComponentState(_currentState, _pauseCallbacks); + State = new PersistentComponentState(_currentState, _registeredCallbacks); _logger = logger; } @@ -48,43 +49,100 @@ public async Task RestoreStateAsync(IPersistentComponentStateStore store) /// The that components are being rendered. /// A that will complete when the state has been restored. public Task PersistStateAsync(IPersistentComponentStateStore store, Renderer renderer) - => PersistStateAsync(store, renderer.Dispatcher); - - /// - /// Persists the component application state into the given . - /// - /// The to restore the application state from. - /// The corresponding to the components' renderer. - /// A that will complete when the state has been restored. - public Task PersistStateAsync(IPersistentComponentStateStore store, Dispatcher dispatcher) { if (_stateIsPersisted) { throw new InvalidOperationException("State already persisted."); } - _stateIsPersisted = true; - - return dispatcher.InvokeAsync(PauseAndPersistState); + return renderer.Dispatcher.InvokeAsync(PauseAndPersistState); async Task PauseAndPersistState() { State.PersistingState = true; - await PauseAsync(); + + if (store is IEnumerable compositeStore) + { + // We only need to do inference when there is more than one store. This is determined by + // the set of rendered components. + InferRenderModes(renderer); + + // Iterate over each store and give it a chance to run against the existing declared + // render modes. After we've run through a store, we clear the current state so that + // the next store can start with a clean slate. + foreach (var store in compositeStore) + { + await PersistState(store); + _currentState.Clear(); + } + } + else + { + await PersistState(store); + } + State.PersistingState = false; + _stateIsPersisted = true; + } + async Task PersistState(IPersistentComponentStateStore store) + { + await PauseAsync(store); await store.PersistStateAsync(_currentState); } } - internal Task PauseAsync() + private void InferRenderModes(Renderer renderer) + { + for (var i = 0; i < _registeredCallbacks.Count; i++) + { + var registration = _registeredCallbacks[i]; + if (registration.RenderMode != null) + { + // Explicitly set render mode, so nothing to do. + continue; + } + + if (registration.Callback.Target is IComponent component) + { + var componentRenderMode = renderer.GetComponentRenderMode(component); + if (componentRenderMode != null) + { + _registeredCallbacks[i] = new PersistComponentStateRegistration(registration.Callback, componentRenderMode); + } + else + { + // If we can't find a render mode, it's an SSR only component and we don't need to + // persist its state at all. + _registeredCallbacks[i] = default; + } + continue; + } + + throw new InvalidOperationException( + $"The registered callback {registration.Callback.Method.Name} must be associated with a component or define" + + $" an explicit render mode type during registration."); + } + } + + internal Task PauseAsync(IPersistentComponentStateStore store) { List? pendingCallbackTasks = null; - for (var i = 0; i < _pauseCallbacks.Count; i++) + for (var i = 0; i < _registeredCallbacks.Count; i++) { - var callback = _pauseCallbacks[i]; - var result = ExecuteCallback(callback, _logger); + var registration = _registeredCallbacks[i]; + + if (!store.SupportsRenderMode(registration.RenderMode!)) + { + // The callback does not have an associated render mode and we are in a multi-store scenario. + // Otherwise, in a single store scenario, we just run the callback. + // If the registration callback is null, it's because it was associated with a component and we couldn't infer + // its render mode, which means is an SSR only component and we don't need to persist its state at all. + continue; + } + + var result = ExecuteCallback(registration.Callback, _logger); if (!result.IsCompletedSuccessfully) { pendingCallbackTasks ??= new(); diff --git a/src/Components/Components/src/PersistComponentStateRegistration.cs b/src/Components/Components/src/PersistComponentStateRegistration.cs new file mode 100644 index 000000000000..0f874970f4e1 --- /dev/null +++ b/src/Components/Components/src/PersistComponentStateRegistration.cs @@ -0,0 +1,13 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +namespace Microsoft.AspNetCore.Components; + +internal readonly struct PersistComponentStateRegistration( + Func callback, + IComponentRenderMode? renderMode) +{ + public Func Callback { get; } = callback; + + public IComponentRenderMode? RenderMode { get; } = renderMode; +} diff --git a/src/Components/Components/src/PersistentComponentState.cs b/src/Components/Components/src/PersistentComponentState.cs index c7dd82965e43..bc193dd77e5f 100644 --- a/src/Components/Components/src/PersistentComponentState.cs +++ b/src/Components/Components/src/PersistentComponentState.cs @@ -15,11 +15,11 @@ public class PersistentComponentState private IDictionary? _existingState; private readonly IDictionary _currentState; - private readonly List> _registeredCallbacks; + private readonly List _registeredCallbacks; internal PersistentComponentState( - IDictionary currentState, - List> pauseCallbacks) + IDictionary currentState, + List pauseCallbacks) { _currentState = currentState; _registeredCallbacks = pauseCallbacks; @@ -43,12 +43,24 @@ internal void InitializeExistingState(IDictionary existingState) /// The callback to invoke when the application is being paused. /// A subscription that can be used to unregister the callback when disposed. public PersistingComponentStateSubscription RegisterOnPersisting(Func callback) + => RegisterOnPersisting(callback, null); + + /// + /// Register a callback to persist the component state when the application is about to be paused. + /// Registered callbacks can use this opportunity to persist their state so that it can be retrieved when the application resumes. + /// + /// The callback to invoke when the application is being paused. + /// + /// A subscription that can be used to unregister the callback when disposed. + public PersistingComponentStateSubscription RegisterOnPersisting(Func callback, IComponentRenderMode? renderMode) { ArgumentNullException.ThrowIfNull(callback); - _registeredCallbacks.Add(callback); + var persistenceCallback = new PersistComponentStateRegistration(callback, renderMode); + + _registeredCallbacks.Add(persistenceCallback); - return new PersistingComponentStateSubscription(_registeredCallbacks, callback); + return new PersistingComponentStateSubscription(_registeredCallbacks, persistenceCallback); } /// diff --git a/src/Components/Components/src/PersistingComponentStateSubscription.cs b/src/Components/Components/src/PersistingComponentStateSubscription.cs index cba41a5de0e3..41e4fb7c4bb1 100644 --- a/src/Components/Components/src/PersistingComponentStateSubscription.cs +++ b/src/Components/Components/src/PersistingComponentStateSubscription.cs @@ -11,10 +11,10 @@ namespace Microsoft.AspNetCore.Components; /// public readonly struct PersistingComponentStateSubscription : IDisposable { - private readonly List>? _callbacks; - private readonly Func? _callback; + private readonly List? _callbacks; + private readonly PersistComponentStateRegistration? _callback; - internal PersistingComponentStateSubscription(List> callbacks, Func callback) + internal PersistingComponentStateSubscription(List callbacks, PersistComponentStateRegistration callback) { _callbacks = callbacks; _callback = callback; @@ -23,9 +23,9 @@ internal PersistingComponentStateSubscription(List> callbacks, Func public void Dispose() { - if (_callback != null) + if (_callback.HasValue) { - _callbacks?.Remove(_callback); + _callbacks?.Remove(_callback.Value); } } } diff --git a/src/Components/Components/src/PublicAPI.Unshipped.txt b/src/Components/Components/src/PublicAPI.Unshipped.txt index aae79b9250c9..49480b8aa1c6 100644 --- a/src/Components/Components/src/PublicAPI.Unshipped.txt +++ b/src/Components/Components/src/PublicAPI.Unshipped.txt @@ -16,11 +16,12 @@ Microsoft.AspNetCore.Components.CascadingValueSource.NotifyChangedAsync( Microsoft.AspNetCore.Components.CascadingValueSource.NotifyChangedAsync(TValue newValue) -> System.Threading.Tasks.Task! Microsoft.AspNetCore.Components.ComponentBase.DispatchExceptionAsync(System.Exception! exception) -> System.Threading.Tasks.Task! Microsoft.AspNetCore.Components.IComponentRenderMode -Microsoft.AspNetCore.Components.Infrastructure.ComponentStatePersistenceManager.PersistStateAsync(Microsoft.AspNetCore.Components.IPersistentComponentStateStore! store, Microsoft.AspNetCore.Components.Dispatcher! dispatcher) -> System.Threading.Tasks.Task! Microsoft.AspNetCore.Components.InjectAttribute.Key.get -> object? Microsoft.AspNetCore.Components.InjectAttribute.Key.init -> void +Microsoft.AspNetCore.Components.IPersistentComponentStateStore.SupportsRenderMode(Microsoft.AspNetCore.Components.IComponentRenderMode! renderMode) -> bool Microsoft.AspNetCore.Components.ParameterView.ToDictionary() -> System.Collections.Generic.IReadOnlyDictionary! *REMOVED*Microsoft.AspNetCore.Components.ParameterView.ToDictionary() -> System.Collections.Generic.IReadOnlyDictionary! +Microsoft.AspNetCore.Components.PersistentComponentState.RegisterOnPersisting(System.Func! callback, Microsoft.AspNetCore.Components.IComponentRenderMode? renderMode) -> Microsoft.AspNetCore.Components.PersistingComponentStateSubscription Microsoft.AspNetCore.Components.RenderHandle.DispatchExceptionAsync(System.Exception! exception) -> System.Threading.Tasks.Task! *REMOVED*Microsoft.AspNetCore.Components.NavigationManager.ToAbsoluteUri(string! relativeUri) -> System.Uri! Microsoft.AspNetCore.Components.NavigationManager.ToAbsoluteUri(string? relativeUri) -> System.Uri! @@ -44,6 +45,7 @@ Microsoft.AspNetCore.Components.RenderTree.NamedEventChangeType Microsoft.AspNetCore.Components.RenderTree.NamedEventChangeType.Added = 0 -> Microsoft.AspNetCore.Components.RenderTree.NamedEventChangeType Microsoft.AspNetCore.Components.RenderTree.NamedEventChangeType.Removed = 1 -> Microsoft.AspNetCore.Components.RenderTree.NamedEventChangeType Microsoft.AspNetCore.Components.RenderTree.RenderBatch.NamedEventChanges.get -> Microsoft.AspNetCore.Components.RenderTree.ArrayRange? +Microsoft.AspNetCore.Components.RenderTree.Renderer.GetComponentState(Microsoft.AspNetCore.Components.IComponent! component) -> Microsoft.AspNetCore.Components.Rendering.ComponentState! Microsoft.AspNetCore.Components.RenderTree.RenderTreeFrame.ComponentFrameFlags.get -> Microsoft.AspNetCore.Components.RenderTree.ComponentFrameFlags Microsoft.AspNetCore.Components.RenderTree.RenderTreeFrameType.ComponentRenderMode = 9 -> Microsoft.AspNetCore.Components.RenderTree.RenderTreeFrameType Microsoft.AspNetCore.Components.RenderTree.RenderTreeFrameType.NamedEvent = 10 -> Microsoft.AspNetCore.Components.RenderTree.RenderTreeFrameType @@ -101,6 +103,7 @@ virtual Microsoft.AspNetCore.Components.Rendering.ComponentState.DisposeAsync() virtual Microsoft.AspNetCore.Components.RenderTree.Renderer.AddPendingTask(Microsoft.AspNetCore.Components.Rendering.ComponentState? componentState, System.Threading.Tasks.Task! task) -> void virtual Microsoft.AspNetCore.Components.RenderTree.Renderer.CreateComponentState(int componentId, Microsoft.AspNetCore.Components.IComponent! component, Microsoft.AspNetCore.Components.Rendering.ComponentState? parentComponentState) -> Microsoft.AspNetCore.Components.Rendering.ComponentState! virtual Microsoft.AspNetCore.Components.RenderTree.Renderer.DispatchEventAsync(ulong eventHandlerId, Microsoft.AspNetCore.Components.RenderTree.EventFieldInfo? fieldInfo, System.EventArgs! eventArgs, bool waitForQuiescence) -> System.Threading.Tasks.Task! +virtual Microsoft.AspNetCore.Components.RenderTree.Renderer.GetComponentRenderMode(Microsoft.AspNetCore.Components.IComponent! component) -> Microsoft.AspNetCore.Components.IComponentRenderMode? virtual Microsoft.AspNetCore.Components.RenderTree.Renderer.ResolveComponentForRenderMode(System.Type! componentType, int? parentComponentId, Microsoft.AspNetCore.Components.IComponentActivator! componentActivator, Microsoft.AspNetCore.Components.IComponentRenderMode! renderMode) -> Microsoft.AspNetCore.Components.IComponent! ~Microsoft.AspNetCore.Components.RenderTree.RenderTreeFrame.ComponentRenderMode.get -> Microsoft.AspNetCore.Components.IComponentRenderMode ~Microsoft.AspNetCore.Components.RenderTree.RenderTreeFrame.NamedEventAssignedName.get -> string diff --git a/src/Components/Components/src/RenderTree/Renderer.cs b/src/Components/Components/src/RenderTree/Renderer.cs index f1ba4a9e2b93..7b96e683131f 100644 --- a/src/Components/Components/src/RenderTree/Renderer.cs +++ b/src/Components/Components/src/RenderTree/Renderer.cs @@ -133,7 +133,20 @@ private static IComponentActivator GetComponentActivatorOrDefault(IServiceProvid protected ComponentState GetComponentState(int componentId) => GetRequiredComponentState(componentId); - internal ComponentState GetComponentState(IComponent component) + /// + /// Gets the for a given component if available. + /// + /// The component type + /// + protected internal virtual IComponentRenderMode? GetComponentRenderMode(IComponent component) + => null; + + /// + /// Resolves the component state for a given instance. + /// + /// The instance + /// + protected internal ComponentState GetComponentState(IComponent component) => _componentStateByComponent.GetValueOrDefault(component); private async void RenderRootComponentsOnHotReload() diff --git a/src/Components/Components/test/Lifetime/ComponentApplicationStateTest.cs b/src/Components/Components/test/Lifetime/ComponentApplicationStateTest.cs index 5d1d6983d91c..bed42d42dfbf 100644 --- a/src/Components/Components/test/Lifetime/ComponentApplicationStateTest.cs +++ b/src/Components/Components/test/Lifetime/ComponentApplicationStateTest.cs @@ -11,7 +11,7 @@ public class ComponentApplicationStateTest public void InitializeExistingState_SetupsState() { // Arrange - var applicationState = new PersistentComponentState(new Dictionary(), new List>()); + var applicationState = new PersistentComponentState(new Dictionary(), new List()); var existingState = new Dictionary { ["MyState"] = JsonSerializer.SerializeToUtf8Bytes(new byte[] { 1, 2, 3, 4 }) @@ -29,7 +29,7 @@ public void InitializeExistingState_SetupsState() public void InitializeExistingState_ThrowsIfAlreadyInitialized() { // Arrange - var applicationState = new PersistentComponentState(new Dictionary(), new List>()); + var applicationState = new PersistentComponentState(new Dictionary(), new List()); var existingState = new Dictionary { ["MyState"] = new byte[] { 1, 2, 3, 4 } @@ -45,7 +45,7 @@ public void InitializeExistingState_ThrowsIfAlreadyInitialized() public void TryRetrieveState_ReturnsStateWhenItExists() { // Arrange - var applicationState = new PersistentComponentState(new Dictionary(), new List>()); + var applicationState = new PersistentComponentState(new Dictionary(), new List()); var existingState = new Dictionary { ["MyState"] = JsonSerializer.SerializeToUtf8Bytes(new byte[] { 1, 2, 3, 4 }) @@ -65,8 +65,10 @@ public void PersistState_SavesDataToTheStoreAsync() { // Arrange var currentState = new Dictionary(); - var applicationState = new PersistentComponentState(currentState, new List>()); - applicationState.PersistingState = true; + var applicationState = new PersistentComponentState(currentState, new List()) + { + PersistingState = true + }; var myState = new byte[] { 1, 2, 3, 4 }; // Act @@ -82,8 +84,10 @@ public void PersistState_ThrowsForDuplicateKeys() { // Arrange var currentState = new Dictionary(); - var applicationState = new PersistentComponentState(currentState, new List>()); - applicationState.PersistingState = true; + var applicationState = new PersistentComponentState(currentState, new List()) + { + PersistingState = true + }; var myState = new byte[] { 1, 2, 3, 4 }; applicationState.PersistAsJson("MyState", myState); @@ -97,8 +101,10 @@ public void PersistAsJson_SerializesTheDataToJsonAsync() { // Arrange var currentState = new Dictionary(); - var applicationState = new PersistentComponentState(currentState, new List>()); - applicationState.PersistingState = true; + var applicationState = new PersistentComponentState(currentState, new List()) + { + PersistingState = true + }; var myState = new byte[] { 1, 2, 3, 4 }; // Act @@ -114,8 +120,10 @@ public void PersistAsJson_NullValueAsync() { // Arrange var currentState = new Dictionary(); - var applicationState = new PersistentComponentState(currentState, new List>()); - applicationState.PersistingState = true; + var applicationState = new PersistentComponentState(currentState, new List()) + { + PersistingState = true + }; // Act applicationState.PersistAsJson("MyState", null); @@ -132,7 +140,7 @@ public void TryRetrieveFromJson_DeserializesTheDataFromJson() var myState = new byte[] { 1, 2, 3, 4 }; var serialized = JsonSerializer.SerializeToUtf8Bytes(myState); var existingState = new Dictionary() { ["MyState"] = serialized }; - var applicationState = new PersistentComponentState(new Dictionary(), new List>()); + var applicationState = new PersistentComponentState(new Dictionary(), new List()); applicationState.InitializeExistingState(existingState); @@ -150,7 +158,7 @@ public void TryRetrieveFromJson_NullValue() // Arrange var serialized = JsonSerializer.SerializeToUtf8Bytes(null); var existingState = new Dictionary() { ["MyState"] = serialized }; - var applicationState = new PersistentComponentState(new Dictionary(), new List>()); + var applicationState = new PersistentComponentState(new Dictionary(), new List()); applicationState.InitializeExistingState(existingState); diff --git a/src/Components/Components/test/Lifetime/ComponentApplicationLifetimeTest.cs b/src/Components/Components/test/Lifetime/ComponentStatePersistenceManagerTest.cs similarity index 82% rename from src/Components/Components/test/Lifetime/ComponentApplicationLifetimeTest.cs rename to src/Components/Components/test/Lifetime/ComponentStatePersistenceManagerTest.cs index 034bd10e5b70..02b104d41f43 100644 --- a/src/Components/Components/test/Lifetime/ComponentApplicationLifetimeTest.cs +++ b/src/Components/Components/test/Lifetime/ComponentStatePersistenceManagerTest.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Buffers; +using System.Collections; using System.Text.Json; using Microsoft.AspNetCore.Components.Infrastructure; using Microsoft.AspNetCore.Components.RenderTree; @@ -12,7 +13,7 @@ namespace Microsoft.AspNetCore.Components; -public class ComponentApplicationLifetimeTest +public class ComponentStatePersistenceManagerTest { [Fact] public async Task RestoreStateAsync_InitializesStateWithDataFromTheProvidedStore() @@ -41,7 +42,7 @@ public async Task RestoreStateAsync_ThrowsOnDoubleInitialization() // Arrange var state = new Dictionary { - ["MyState"] = new byte[] { 0, 1, 2, 3, 4 } + ["MyState"] = [0, 1, 2, 3, 4] }; var store = new TestStore(state); var lifetime = new ComponentStatePersistenceManager(NullLogger.Instance); @@ -52,6 +53,28 @@ public async Task RestoreStateAsync_ThrowsOnDoubleInitialization() await Assert.ThrowsAsync(() => lifetime.RestoreStateAsync(store)); } + [Fact] + public async Task PersistStateAsync_ThrowsWhenCallbackRenerModeCannotBeInferred() + { + // Arrange + var state = new Dictionary(); + var store = new CompositeTestStore(state); + var lifetime = new ComponentStatePersistenceManager(NullLogger.Instance); + + var renderer = new TestRenderer(); + var data = new byte[] { 1, 2, 3, 4 }; + + lifetime.State.RegisterOnPersisting(() => + { + lifetime.State.PersistAsJson("MyState", new byte[] { 1, 2, 3, 4 }); + return Task.CompletedTask; + }); + + // Act + // Assert + await Assert.ThrowsAsync(() => lifetime.PersistStateAsync(store, renderer)); + } + [Fact] public async Task PersistStateAsync_SavesPersistedStateToTheStore() { @@ -67,7 +90,7 @@ public async Task PersistStateAsync_SavesPersistedStateToTheStore() { lifetime.State.PersistAsJson("MyState", new byte[] { 1, 2, 3, 4 }); return Task.CompletedTask; - }); + }, new TestRenderMode()); // Act await lifetime.PersistStateAsync(store, renderer); @@ -88,7 +111,7 @@ public async Task PersistStateAsync_InvokesPauseCallbacksDuringPersist() var data = new byte[] { 1, 2, 3, 4 }; var invoked = false; - lifetime.State.RegisterOnPersisting(() => { invoked = true; return default; }); + lifetime.State.RegisterOnPersisting(() => { invoked = true; return default; }, new TestRenderMode()); // Act await lifetime.PersistStateAsync(store, renderer); @@ -111,8 +134,8 @@ public async Task PersistStateAsync_FiresCallbacksInParallel() var tcs = new TaskCompletionSource(); var tcs2 = new TaskCompletionSource(); - lifetime.State.RegisterOnPersisting(async () => { sequence.Add(1); await tcs.Task; sequence.Add(3); }); - lifetime.State.RegisterOnPersisting(async () => { sequence.Add(2); await tcs2.Task; sequence.Add(4); }); + lifetime.State.RegisterOnPersisting(async () => { sequence.Add(1); await tcs.Task; sequence.Add(3); }, new TestRenderMode()); + lifetime.State.RegisterOnPersisting(async () => { sequence.Add(2); await tcs2.Task; sequence.Add(4); }, new TestRenderMode()); // Act var persistTask = lifetime.PersistStateAsync(store, renderer); @@ -170,8 +193,8 @@ public async Task PersistStateAsync_ContinuesInvokingPauseCallbacksDuringPersist var data = new byte[] { 1, 2, 3, 4 }; var invoked = false; - lifetime.State.RegisterOnPersisting(() => throw new InvalidOperationException()); - lifetime.State.RegisterOnPersisting(() => { invoked = true; return Task.CompletedTask; }); + lifetime.State.RegisterOnPersisting(() => throw new InvalidOperationException(), new TestRenderMode()); + lifetime.State.RegisterOnPersisting(() => { invoked = true; return Task.CompletedTask; }, new TestRenderMode()); // Act await lifetime.PersistStateAsync(store, renderer); @@ -196,8 +219,8 @@ public async Task PersistStateAsync_ContinuesInvokingPauseCallbacksDuringPersist var invoked = false; var tcs = new TaskCompletionSource(); - lifetime.State.RegisterOnPersisting(async () => { await tcs.Task; throw new InvalidOperationException(); }); - lifetime.State.RegisterOnPersisting(() => { invoked = true; return Task.CompletedTask; }); + lifetime.State.RegisterOnPersisting(async () => { await tcs.Task; throw new InvalidOperationException(); }, new TestRenderMode()); + lifetime.State.RegisterOnPersisting(() => { invoked = true; return Task.CompletedTask; }, new TestRenderMode()); // Act var persistTask = lifetime.PersistStateAsync(store, renderer); @@ -211,30 +234,6 @@ public async Task PersistStateAsync_ContinuesInvokingPauseCallbacksDuringPersist Assert.Equal(LogLevel.Error, log.LogLevel); } - [Fact] - public async Task PersistStateAsync_ThrowsWhenDeveloperTriesToPersistStateMultipleTimes() - { - // Arrange - var state = new Dictionary(); - var store = new TestStore(state); - var lifetime = new ComponentStatePersistenceManager(NullLogger.Instance); - - var renderer = new TestRenderer(); - var data = new byte[] { 1, 2, 3, 4 }; - - lifetime.State.RegisterOnPersisting(() => - { - lifetime.State.PersistAsJson("MyState", new byte[] { 1, 2, 3, 4 }); - return Task.CompletedTask; - }); - - // Act - await lifetime.PersistStateAsync(store, renderer); - - // Assert - await Assert.ThrowsAsync(() => lifetime.PersistStateAsync(store, renderer)); - } - private class TestRenderer : Renderer { public TestRenderer() : base(new ServiceCollection().BuildServiceProvider(), NullLoggerFactory.Instance) @@ -277,4 +276,42 @@ public Task PersistStateAsync(IReadOnlyDictionary state) return Task.CompletedTask; } } + + private class CompositeTestStore : IPersistentComponentStateStore, IEnumerable + { + public CompositeTestStore(IDictionary initialState) + { + State = initialState; + } + + public IDictionary State { get; set; } + + public IEnumerator GetEnumerator() + { + yield return new TestStore(State); + yield return new TestStore(State); + } + + public Task> GetPersistedStateAsync() + { + return Task.FromResult(State); + } + + public Task PersistStateAsync(IReadOnlyDictionary state) + { + // We copy the data here because it's no longer available after this call completes. + State = state.ToDictionary(k => k.Key, v => v.Value); + return Task.CompletedTask; + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + } + + private class TestRenderMode : IComponentRenderMode + { + + } } diff --git a/src/Components/Endpoints/src/RazorComponentEndpointInvoker.cs b/src/Components/Endpoints/src/RazorComponentEndpointInvoker.cs index 7dafc88bafab..48f9eacfe104 100644 --- a/src/Components/Endpoints/src/RazorComponentEndpointInvoker.cs +++ b/src/Components/Endpoints/src/RazorComponentEndpointInvoker.cs @@ -121,6 +121,10 @@ await EndpointHtmlRenderer.InitializeStandardComponentServicesAsync( await _renderer.SendStreamingUpdatesAsync(context, quiesceTask, bufferWriter); } + // Emit comment containing state. + var componentStateHtmlContent = await _renderer.PrerenderPersistedStateAsync(context); + componentStateHtmlContent.WriteTo(bufferWriter, HtmlEncoder.Default); + // Invoke FlushAsync to ensure any buffered content is asynchronously written to the underlying // response asynchronously. In the absence of this line, the buffer gets synchronously written to the // response as part of the Dispose which has a perf impact. diff --git a/src/Components/Endpoints/src/Rendering/EndpointHtmlRenderer.Prerendering.cs b/src/Components/Endpoints/src/Rendering/EndpointHtmlRenderer.Prerendering.cs index 3b192d99552b..6a2d399e3520 100644 --- a/src/Components/Endpoints/src/Rendering/EndpointHtmlRenderer.Prerendering.cs +++ b/src/Components/Endpoints/src/Rendering/EndpointHtmlRenderer.Prerendering.cs @@ -3,6 +3,7 @@ using System.Diagnostics.CodeAnalysis; using System.Text.Encodings.Web; +using Microsoft.AspNetCore.Components.Rendering; using Microsoft.AspNetCore.Components.Web.HtmlRendering; using Microsoft.AspNetCore.Html; using Microsoft.AspNetCore.Http; @@ -33,19 +34,39 @@ protected override IComponent ResolveComponentForRenderMode([DynamicallyAccessed } } + protected override IComponentRenderMode? GetComponentRenderMode(IComponent component) + { + var componentState = GetComponentState(component); + var ssrRenderBoundary = GetClosestRenderModeBoundary(componentState); + + if (ssrRenderBoundary is null) + { + return null; + } + + return ssrRenderBoundary.RenderMode; + } + private SSRRenderModeBoundary? GetClosestRenderModeBoundary(int componentId) { var componentState = GetComponentState(componentId); + return GetClosestRenderModeBoundary(componentState); + } + + private static SSRRenderModeBoundary? GetClosestRenderModeBoundary(ComponentState componentState) + { + var currentComponentState = componentState; + do { - if (componentState.Component is SSRRenderModeBoundary boundary) + if (currentComponentState.Component is SSRRenderModeBoundary boundary) { return boundary; } - componentState = componentState.ParentComponentState; + currentComponentState = currentComponentState.ParentComponentState; } - while (componentState is not null); + while (currentComponentState is not null); return null; } diff --git a/src/Components/Endpoints/src/Rendering/EndpointHtmlRenderer.PrerenderingState.cs b/src/Components/Endpoints/src/Rendering/EndpointHtmlRenderer.PrerenderingState.cs index 3b710374d38f..161967076ec5 100644 --- a/src/Components/Endpoints/src/Rendering/EndpointHtmlRenderer.PrerenderingState.cs +++ b/src/Components/Endpoints/src/Rendering/EndpointHtmlRenderer.PrerenderingState.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using System.Collections; using System.Text.Encodings.Web; using Microsoft.AspNetCore.Components.Infrastructure; using Microsoft.AspNetCore.Components.Web; @@ -15,6 +16,98 @@ internal partial class EndpointHtmlRenderer { private static readonly object InvokedRenderModesKey = new object(); + public async ValueTask PrerenderPersistedStateAsync(HttpContext httpContext) + { + SetHttpContext(httpContext); + + var manager = _httpContext.RequestServices.GetRequiredService(); + + var renderModesMetadata = httpContext.GetEndpoint()?.Metadata.GetMetadata(); + + IPersistentComponentStateStore? store = null; + + // There is configured render modes metadata, use this to determine where to persist state if possible + if (renderModesMetadata != null) + { + // No render modes are configured, do not persist state + if (renderModesMetadata.ConfiguredRenderModes.Length == 0) + { + return ComponentStateHtmlContent.Empty; + } + + // Single render mode, no need to perform inference. Any component that tried to render an + // incompatible render mode would have failed at this point. + if (renderModesMetadata.ConfiguredRenderModes.Length == 1) + { + store = renderModesMetadata.ConfiguredRenderModes[0] switch + { + InteractiveServerRenderMode => new ProtectedPrerenderComponentApplicationStore(_httpContext.RequestServices.GetRequiredService()), + InteractiveWebAssemblyRenderMode => new PrerenderComponentApplicationStore(), + _ => throw new InvalidOperationException("Invalid configured render mode."), + }; + } + } + + if (store != null) + { + await manager.PersistStateAsync(store, this); + return store switch + { + ProtectedPrerenderComponentApplicationStore protectedStore => new ComponentStateHtmlContent(protectedStore, null), + PrerenderComponentApplicationStore prerenderStore => new ComponentStateHtmlContent(null, prerenderStore), + _ => throw new InvalidOperationException("Invalid store."), + }; + } + else + { + // We were not able to resolve a store from the configured render modes metadata, we need to capture + // all possible destinations for the state and persist it in all of them. + var serverStore = new ProtectedPrerenderComponentApplicationStore(_httpContext.RequestServices.GetRequiredService()); + var webAssemblyStore = new PrerenderComponentApplicationStore(); + + // The persistence state manager checks if the store implements + // IEnumerable and if so, it invokes PersistStateAsync on each store + // for each of the render mode callbacks defined. + // We pass in a composite store with fake stores for each render mode that only take care of + // creating a copy of the state for each render mode. + // Then, we copy the state from the auto store to the server and webassembly stores and persist + // the real state for server and webassembly render modes. + // This makes sure that: + // 1. The persistence state manager is agnostic to the render modes. + // 2. The callbacks are run only once, even if the state ends up persisted in multiple locations. + var server = new CopyOnlyStore(); + var auto = new CopyOnlyStore(); + var webAssembly = new CopyOnlyStore(); + store = new CompositeStore(server, auto, webAssembly); + + await manager.PersistStateAsync(store, this); + + foreach (var kvp in auto.Saved) + { + server.Saved.Add(kvp.Key, kvp.Value); + webAssembly.Saved.Add(kvp.Key, kvp.Value); + } + + // Persist state only if there is state to persist + var saveServerTask = server.Saved.Count > 0 + ? serverStore.PersistStateAsync(server.Saved) + : Task.CompletedTask; + + var saveWebAssemblyTask = webAssembly.Saved.Count > 0 + ? webAssemblyStore.PersistStateAsync(webAssembly.Saved) + : Task.CompletedTask; + + await Task.WhenAll( + saveServerTask, + saveWebAssemblyTask); + + // Do not return any HTML content if there is no state to persist for a given mode. + return new ComponentStateHtmlContent( + server.Saved.Count > 0 ? serverStore : null, + webAssembly.Saved.Count > 0 ? webAssemblyStore : null); + } + } + public async ValueTask PrerenderPersistedStateAsync(HttpContext httpContext, PersistedStateSerializationMode serializationMode) { SetHttpContext(httpContext); @@ -40,21 +133,25 @@ public async ValueTask PrerenderPersistedStateAsync(HttpContext ht } } + var manager = _httpContext.RequestServices.GetRequiredService(); + // Now given the mode, we obtain a particular store for that mode - var store = serializationMode switch + // and persist the state and return the HTML content + switch (serializationMode) { - PersistedStateSerializationMode.Server => - new ProtectedPrerenderComponentApplicationStore(_httpContext.RequestServices.GetRequiredService()), - PersistedStateSerializationMode.WebAssembly => - new PrerenderComponentApplicationStore(), - _ => - throw new InvalidOperationException("Invalid persistence mode.") - }; - - // Finally, persist the state and return the HTML content - var manager = _httpContext.RequestServices.GetRequiredService(); - await manager.PersistStateAsync(store, Dispatcher); - return new ComponentStateHtmlContent(store); + case PersistedStateSerializationMode.Server: + var protectedStore = new ProtectedPrerenderComponentApplicationStore(_httpContext.RequestServices.GetRequiredService()); + await manager.PersistStateAsync(protectedStore, this); + return new ComponentStateHtmlContent(protectedStore, null); + + case PersistedStateSerializationMode.WebAssembly: + var store = new PrerenderComponentApplicationStore(); + await manager.PersistStateAsync(store, this); + return new ComponentStateHtmlContent(null, store); + + default: + throw new InvalidOperationException("Invalid persistence mode."); + } } // Internal for test only @@ -101,27 +198,80 @@ internal static InvokedRenderModes.Mode GetPersistStateRenderMode(HttpContext ht : InvokedRenderModes.Mode.None; } - private sealed class ComponentStateHtmlContent : IHtmlContent + internal sealed class ComponentStateHtmlContent : IHtmlContent { - private PrerenderComponentApplicationStore? _store; + public static ComponentStateHtmlContent Empty { get; } = new(null, null); + + internal PrerenderComponentApplicationStore? ServerStore { get; } - public static ComponentStateHtmlContent Empty { get; } - = new ComponentStateHtmlContent(null); + internal PrerenderComponentApplicationStore? WebAssemblyStore { get; } - public ComponentStateHtmlContent(PrerenderComponentApplicationStore? store) + public ComponentStateHtmlContent(PrerenderComponentApplicationStore? serverStore, PrerenderComponentApplicationStore? webAssemblyStore) { - _store = store; + WebAssemblyStore = webAssemblyStore; + ServerStore = serverStore; } public void WriteTo(TextWriter writer, HtmlEncoder encoder) { - if (_store != null) + if (ServerStore is not null && ServerStore.PersistedState is not null) { - writer.Write(""); - _store = null; } + + if (WebAssemblyStore is not null && WebAssemblyStore.PersistedState is not null) + { + writer.Write(""); + } + } + } + + internal class CompositeStore : IPersistentComponentStateStore, IEnumerable + { + public CompositeStore( + CopyOnlyStore server, + CopyOnlyStore auto, + CopyOnlyStore webassembly) + { + Server = server; + Auto = auto; + Webassembly = webassembly; + } + + public CopyOnlyStore Server { get; } + public CopyOnlyStore Auto { get; } + public CopyOnlyStore Webassembly { get; } + + public IEnumerator GetEnumerator() + { + yield return Server; + yield return Auto; + yield return Webassembly; + } + + public Task> GetPersistedStateAsync() => throw new NotImplementedException(); + + public Task PersistStateAsync(IReadOnlyDictionary state) => Task.CompletedTask; + + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + } + + internal class CopyOnlyStore : IPersistentComponentStateStore where T : IComponentRenderMode + { + public Dictionary Saved { get; private set; } = new(); + + public Task> GetPersistedStateAsync() => throw new NotImplementedException(); + + public Task PersistStateAsync(IReadOnlyDictionary state) + { + Saved = new Dictionary(state); + return Task.CompletedTask; } + + public bool SupportsRenderMode(IComponentRenderMode renderMode) => renderMode is T; } } diff --git a/src/Components/Endpoints/src/Rendering/SSRRenderModeBoundary.cs b/src/Components/Endpoints/src/Rendering/SSRRenderModeBoundary.cs index 66a9331c0f1a..b0b4d9510901 100644 --- a/src/Components/Endpoints/src/Rendering/SSRRenderModeBoundary.cs +++ b/src/Components/Endpoints/src/Rendering/SSRRenderModeBoundary.cs @@ -26,12 +26,13 @@ internal class SSRRenderModeBoundary : IComponent [DynamicallyAccessedMembers(Component)] private readonly Type _componentType; - private readonly IComponentRenderMode _renderMode; private readonly bool _prerender; private RenderHandle _renderHandle; private IReadOnlyDictionary? _latestParameters; private string? _markerKey; + public IComponentRenderMode RenderMode { get; } + public SSRRenderModeBoundary( HttpContext httpContext, [DynamicallyAccessedMembers(Component)] Type componentType, @@ -40,7 +41,7 @@ public SSRRenderModeBoundary( AssertRenderModeIsConfigured(httpContext, componentType, renderMode); _componentType = componentType; - _renderMode = renderMode; + RenderMode = renderMode; _prerender = renderMode switch { InteractiveServerRenderMode mode => mode.Prerender, @@ -76,7 +77,7 @@ private static void AssertRenderModeIsConfigured(HttpContext httpContext, Type c } } - private static void AssertRenderModeIsConfigured(Type componentType, IComponentRenderMode specifiedMode, IComponentRenderMode[] configuredModes, string expectedCall) where TRequiredMode: IComponentRenderMode + private static void AssertRenderModeIsConfigured(Type componentType, IComponentRenderMode specifiedMode, IComponentRenderMode[] configuredModes, string expectedCall) where TRequiredMode : IComponentRenderMode { foreach (var configuredMode in configuredModes) { @@ -126,7 +127,7 @@ private void ValidateParameters(IReadOnlyDictionary latestParam var valueType = value.GetType(); if (valueType.IsGenericType && valueType.GetGenericTypeDefinition() == typeof(RenderFragment<>)) { - throw new InvalidOperationException($"Cannot pass RenderFragment parameter '{name}' to component '{_componentType.Name}' with rendermode '{_renderMode.GetType().Name}'. Templated content can't be passed across a rendermode boundary, because it is arbitrary code and cannot be serialized."); + throw new InvalidOperationException($"Cannot pass RenderFragment parameter '{name}' to component '{_componentType.Name}' with rendermode '{RenderMode.GetType().Name}'. Templated content can't be passed across a rendermode boundary, because it is arbitrary code and cannot be serialized."); } else { @@ -135,7 +136,7 @@ private void ValidateParameters(IReadOnlyDictionary latestParam // somehow without actually emitting its result directly, wait for quiescence, and then prerender // the output into a separate buffer so we can serialize it in a special way. // A prototype implementation is at https://github.com/dotnet/aspnetcore/commit/ed330ff5b143974d9060828a760ad486b1d386ac - throw new InvalidOperationException($"Cannot pass the parameter '{name}' to component '{_componentType.Name}' with rendermode '{_renderMode.GetType().Name}'. This is because the parameter is of the delegate type '{value.GetType()}', which is arbitrary code and cannot be serialized."); + throw new InvalidOperationException($"Cannot pass the parameter '{name}' to component '{_componentType.Name}' with rendermode '{RenderMode.GetType().Name}'. This is because the parameter is of the delegate type '{value.GetType()}', which is arbitrary code and cannot be serialized."); } } } @@ -163,15 +164,15 @@ public ComponentMarker ToMarker(HttpContext httpContext, int sequence, object? k ? ParameterView.Empty : ParameterView.FromDictionary((IDictionary)_latestParameters); - var marker = _renderMode switch + var marker = RenderMode switch { InteractiveServerRenderMode server => ComponentMarker.Create(ComponentMarker.ServerMarkerType, server.Prerender, _markerKey), InteractiveWebAssemblyRenderMode webAssembly => ComponentMarker.Create(ComponentMarker.WebAssemblyMarkerType, webAssembly.Prerender, _markerKey), InteractiveAutoRenderMode auto => ComponentMarker.Create(ComponentMarker.AutoMarkerType, auto.Prerender, _markerKey), - _ => throw new UnreachableException($"Unknown render mode {_renderMode.GetType().FullName}"), + _ => throw new UnreachableException($"Unknown render mode {RenderMode.GetType().FullName}"), }; - if (_renderMode is InteractiveServerRenderMode or InteractiveAutoRenderMode) + if (RenderMode is InteractiveServerRenderMode or InteractiveAutoRenderMode) { // Lazy because we don't actually want to require a whole chain of services including Data Protection // to be required unless you actually use Server render mode. @@ -181,7 +182,7 @@ public ComponentMarker ToMarker(HttpContext httpContext, int sequence, object? k serverComponentSerializer.SerializeInvocation(ref marker, invocationId, _componentType, parameters); } - if (_renderMode is InteractiveWebAssemblyRenderMode or InteractiveAutoRenderMode) + if (RenderMode is InteractiveWebAssemblyRenderMode or InteractiveAutoRenderMode) { WebAssemblyComponentSerializer.SerializeInvocation(ref marker, _componentType, parameters); } diff --git a/src/Components/Endpoints/test/EndpointHtmlRendererTest.cs b/src/Components/Endpoints/test/EndpointHtmlRendererTest.cs index 65c4d0692051..ec85442c9e5f 100644 --- a/src/Components/Endpoints/test/EndpointHtmlRendererTest.cs +++ b/src/Components/Endpoints/test/EndpointHtmlRendererTest.cs @@ -10,6 +10,7 @@ using Microsoft.AspNetCore.Components.Forms; using Microsoft.AspNetCore.Components.Forms.Mapping; using Microsoft.AspNetCore.Components.Infrastructure; +using Microsoft.AspNetCore.Components.Reflection; using Microsoft.AspNetCore.Components.Rendering; using Microsoft.AspNetCore.Components.Test.Helpers; using Microsoft.AspNetCore.Components.Web; @@ -1177,6 +1178,326 @@ public async Task DoesNotEmitNestedRenderModeBoundaries() Assert.Equal("

This is InteractiveWithInteractiveChild

\n\n

Hello from InteractiveGreetingServer!

", prerenderedContent.Replace("\r\n", "\n")); } + [Fact] + public async Task PrerenderedState_EmptyWhenNoDeclaredRenderModes() + { + var declaredRenderModesMetadata = new ConfiguredRenderModesMetadata([]); + var endpoint = new Endpoint((context) => Task.CompletedTask, new EndpointMetadataCollection(declaredRenderModesMetadata), + "TestEndpoint"); + + var httpContext = GetHttpContext(); + httpContext.SetEndpoint(endpoint); + var content = await renderer.PrerenderPersistedStateAsync(httpContext); + + Assert.Equal(EndpointHtmlRenderer.ComponentStateHtmlContent.Empty, content); + } + + public static TheoryData SingleComponentRenderModeData => new TheoryData + { + RenderMode.InteractiveServer, + RenderMode.InteractiveWebAssembly + }; + + [Theory] + [MemberData(nameof(SingleComponentRenderModeData))] + public async Task PrerenderedState_SelectsSingleStoreCorrectly(IComponentRenderMode renderMode) + { + var declaredRenderModesMetadata = new ConfiguredRenderModesMetadata([renderMode]); + var endpoint = new Endpoint((context) => Task.CompletedTask, new EndpointMetadataCollection(declaredRenderModesMetadata), + "TestEndpoint"); + + var httpContext = GetHttpContext(); + httpContext.SetEndpoint(endpoint); + var content = await renderer.PrerenderPersistedStateAsync(httpContext); + + Assert.NotNull(content); + var stateContent = Assert.IsType(content); + switch (renderMode) + { + case InteractiveServerRenderMode: + Assert.NotNull(stateContent.ServerStore); + Assert.Null(stateContent.ServerStore.PersistedState); + Assert.Null(stateContent.WebAssemblyStore); + break; + case InteractiveWebAssemblyRenderMode: + Assert.NotNull(stateContent.WebAssemblyStore); + Assert.Null(stateContent.WebAssemblyStore.PersistedState); + Assert.Null(stateContent.ServerStore); + break; + default: + throw new InvalidOperationException($"Unexpected render mode: {renderMode}"); + } + } + + [Fact] + public async Task PrerenderedState_MultipleStoresCorrectly() + { + var declaredRenderModesMetadata = new ConfiguredRenderModesMetadata([RenderMode.InteractiveServer, RenderMode.InteractiveWebAssembly]); + var endpoint = new Endpoint((context) => Task.CompletedTask, new EndpointMetadataCollection(declaredRenderModesMetadata), + "TestEndpoint"); + + var httpContext = GetHttpContext(); + httpContext.SetEndpoint(endpoint); + var content = await renderer.PrerenderPersistedStateAsync(httpContext); + + Assert.NotNull(content); + var stateContent = Assert.IsType(content); + Assert.Null(stateContent.ServerStore); + Assert.Null(stateContent.WebAssemblyStore); + } + + [Theory] + [InlineData("server")] + [InlineData("wasm")] + [InlineData("auto")] + public async Task PrerenderedState_PersistToStores_OnlyWhenContentIsAvailable(string renderMode) + { + IComponentRenderMode persistenceMode = renderMode switch + { + "server" => RenderMode.InteractiveServer, + "wasm" => RenderMode.InteractiveWebAssembly, + "auto" => RenderMode.InteractiveAuto, + _ => throw new InvalidOperationException($"Unexpected render mode: {renderMode}"), + }; + + var declaredRenderModesMetadata = new ConfiguredRenderModesMetadata([RenderMode.InteractiveServer, RenderMode.InteractiveWebAssembly]); + var endpoint = new Endpoint((context) => Task.CompletedTask, new EndpointMetadataCollection(declaredRenderModesMetadata), + "TestEndpoint"); + + var httpContext = GetHttpContext(); + httpContext.SetEndpoint(endpoint); + var state = httpContext.RequestServices.GetRequiredService(); + + state.RegisterOnPersisting(() => + { + state.PersistAsJson(renderMode, "persisted"); + return Task.CompletedTask; + }, persistenceMode); + + var content = await renderer.PrerenderPersistedStateAsync(httpContext); + + Assert.NotNull(content); + var stateContent = Assert.IsType(content); + switch (persistenceMode) + { + case InteractiveServerRenderMode: + Assert.NotNull(stateContent.ServerStore); + Assert.NotNull(stateContent.ServerStore.PersistedState); + Assert.Null(stateContent.WebAssemblyStore); + break; + case InteractiveWebAssemblyRenderMode: + Assert.NotNull(stateContent.WebAssemblyStore); + Assert.NotNull(stateContent.WebAssemblyStore.PersistedState); + Assert.Null(stateContent.ServerStore); + break; + case InteractiveAutoRenderMode: + Assert.NotNull(stateContent.ServerStore); + Assert.NotNull(stateContent.ServerStore.PersistedState); + Assert.NotNull(stateContent.WebAssemblyStore); + Assert.NotNull(stateContent.WebAssemblyStore.PersistedState); + break; + default: + break; + } + } + + [Theory] + [InlineData("server")] + [InlineData("wasm")] + public async Task PrerenderedState_PersistToStores_DoesNotNeedToInferRenderMode_ForSingleRenderMode(string declaredRenderMode) + { + IComponentRenderMode configuredMode = declaredRenderMode switch + { + "server" => RenderMode.InteractiveServer, + "wasm" => RenderMode.InteractiveWebAssembly, + "auto" => RenderMode.InteractiveAuto, + _ => throw new InvalidOperationException($"Unexpected render mode: {declaredRenderMode}"), + }; + + var declaredRenderModesMetadata = new ConfiguredRenderModesMetadata([configuredMode]); + var endpoint = new Endpoint((context) => Task.CompletedTask, new EndpointMetadataCollection(declaredRenderModesMetadata), + "TestEndpoint"); + + var httpContext = GetHttpContext(); + httpContext.SetEndpoint(endpoint); + var state = httpContext.RequestServices.GetRequiredService(); + + state.RegisterOnPersisting(() => + { + state.PersistAsJson("key", "persisted"); + return Task.CompletedTask; + }); + + var content = await renderer.PrerenderPersistedStateAsync(httpContext); + + Assert.NotNull(content); + var stateContent = Assert.IsType(content); + switch (configuredMode) + { + case InteractiveServerRenderMode: + Assert.NotNull(stateContent.ServerStore); + Assert.NotNull(stateContent.ServerStore.PersistedState); + Assert.Null(stateContent.WebAssemblyStore); + break; + case InteractiveWebAssemblyRenderMode: + Assert.NotNull(stateContent.WebAssemblyStore); + Assert.NotNull(stateContent.WebAssemblyStore.PersistedState); + Assert.Null(stateContent.ServerStore); + break; + default: + break; + } + } + + [Fact] + public async Task PrerenderedState_Throws_WhenItCanInfer_CallbackRenderMode_ForMultipleRenderModes() + { + var declaredRenderModesMetadata = new ConfiguredRenderModesMetadata([RenderMode.InteractiveServer, RenderMode.InteractiveWebAssembly]); + var endpoint = new Endpoint((context) => Task.CompletedTask, new EndpointMetadataCollection(declaredRenderModesMetadata), + "TestEndpoint"); + + var httpContext = GetHttpContext(); + httpContext.SetEndpoint(endpoint); + var state = httpContext.RequestServices.GetRequiredService(); + + state.RegisterOnPersisting(() => + { + state.PersistAsJson("key", "persisted"); + return Task.CompletedTask; + }); + + await Assert.ThrowsAsync(async () => await renderer.PrerenderPersistedStateAsync(httpContext)); + } + + [Theory] + [InlineData("server")] + [InlineData("auto")] + [InlineData("wasm")] + public async Task PrerenderedState_InfersCallbackRenderMode_ForMultipleRenderModes(string renderMode) + { + IComponentRenderMode persistenceMode = renderMode switch + { + "server" => RenderMode.InteractiveServer, + "wasm" => RenderMode.InteractiveWebAssembly, + "auto" => RenderMode.InteractiveAuto, + _ => throw new InvalidOperationException($"Unexpected render mode: {renderMode}"), + }; + var declaredRenderModesMetadata = new ConfiguredRenderModesMetadata([RenderMode.InteractiveServer, RenderMode.InteractiveWebAssembly]); + var endpoint = new Endpoint((context) => Task.CompletedTask, new EndpointMetadataCollection(declaredRenderModesMetadata), + "TestEndpoint"); + + var httpContext = GetHttpContext(); + httpContext.SetEndpoint(endpoint); + var state = httpContext.RequestServices.GetRequiredService(); + + var ssrBoundary = new SSRRenderModeBoundary(httpContext, typeof(PersistenceComponent), persistenceMode); + var id = renderer.AssignRootComponentId(ssrBoundary); + + await renderer.Dispatcher.InvokeAsync(() => renderer.RenderRootComponentAsync(id, ParameterView.Empty)); + + var content = await renderer.PrerenderPersistedStateAsync(httpContext); + Assert.NotNull(content); + var stateContent = Assert.IsType(content); + switch (persistenceMode) + { + case InteractiveServerRenderMode: + Assert.NotNull(stateContent.ServerStore); + Assert.NotNull(stateContent.ServerStore.PersistedState); + Assert.Null(stateContent.WebAssemblyStore); + break; + case InteractiveWebAssemblyRenderMode: + Assert.NotNull(stateContent.WebAssemblyStore); + Assert.NotNull(stateContent.WebAssemblyStore.PersistedState); + Assert.Null(stateContent.ServerStore); + break; + case InteractiveAutoRenderMode: + Assert.NotNull(stateContent.ServerStore); + Assert.NotNull(stateContent.ServerStore.PersistedState); + Assert.NotNull(stateContent.WebAssemblyStore); + Assert.NotNull(stateContent.WebAssemblyStore.PersistedState); + break; + default: + break; + } + } + + [Theory] + [InlineData("server", "server", true)] + [InlineData("auto", "server", true)] + [InlineData("auto", "wasm", true)] + [InlineData("wasm", "wasm", true)] + // Note that when an incompatible explicit render mode is specified we don't serialize the data. + [InlineData("server", "wasm", false)] + [InlineData("wasm", "server", false)] + public async Task PrerenderedState_ExplicitRenderModes_AreRespected(string renderMode, string declared, bool persisted) + { + IComponentRenderMode persistenceMode = renderMode switch + { + "server" => RenderMode.InteractiveServer, + "wasm" => RenderMode.InteractiveWebAssembly, + "auto" => RenderMode.InteractiveAuto, + _ => throw new InvalidOperationException($"Unexpected render mode: {renderMode}"), + }; + + IComponentRenderMode configuredMode = declared switch + { + "server" => RenderMode.InteractiveServer, + "wasm" => RenderMode.InteractiveWebAssembly, + "auto" => RenderMode.InteractiveAuto, + _ => throw new InvalidOperationException($"Unexpected render mode: {declared}"), + }; + + var declaredRenderModesMetadata = new ConfiguredRenderModesMetadata([configuredMode]); + var endpoint = new Endpoint((context) => Task.CompletedTask, new EndpointMetadataCollection(declaredRenderModesMetadata), + "TestEndpoint"); + + var httpContext = GetHttpContext(); + httpContext.SetEndpoint(endpoint); + var state = httpContext.RequestServices.GetRequiredService(); + + var ssrBoundary = new SSRRenderModeBoundary(httpContext, typeof(PersistenceComponent), configuredMode); + var id = renderer.AssignRootComponentId(ssrBoundary); + await renderer.Dispatcher.InvokeAsync(() => renderer.RenderRootComponentAsync( + id, + ParameterView.FromDictionary(new Dictionary + { + ["Mode"] = renderMode, + }))); + + var content = await renderer.PrerenderPersistedStateAsync(httpContext); + Assert.NotNull(content); + var stateContent = Assert.IsType(content); + switch (configuredMode) + { + case InteractiveServerRenderMode: + if (persisted) + { + Assert.NotNull(stateContent.ServerStore); + Assert.NotNull(stateContent.ServerStore.PersistedState); + } + else + { + Assert.Null(stateContent.ServerStore.PersistedState); + } + Assert.Null(stateContent.WebAssemblyStore); + break; + case InteractiveWebAssemblyRenderMode: + if (persisted) + { + Assert.NotNull(stateContent.WebAssemblyStore); + Assert.NotNull(stateContent.WebAssemblyStore.PersistedState); + } + else + { + Assert.Null(stateContent.WebAssemblyStore.PersistedState); + } + Assert.Null(stateContent.ServerStore); + break; + default: + break; + } + } + private class NamedEventHandlerComponent : ComponentBase { [Parameter] @@ -1230,7 +1551,7 @@ protected override void BuildRenderTree(RenderTreeBuilder builder) builder.OpenElement(0, "form"); builder.AddAttribute(1, "onsubmit", !hasRendered ? () => { Message = "Received call to original handler"; } - : () => { Message = "Received call to updated handler"; }); + : () => { Message = "Received call to updated handler"; }); builder.AddNamedEvent("onsubmit", "default"); builder.CloseElement(); } @@ -1266,6 +1587,44 @@ protected override void BuildRenderTree(RenderTreeBuilder builder) => _renderFragment(builder); } + class PersistenceComponent : IComponent + { + [Inject] public PersistentComponentState State { get; set; } + + [Parameter] public string Mode { get; set; } + + private Task PersistState() + { + State.PersistAsJson("key", "value"); + return Task.CompletedTask; + } + + public void Attach(RenderHandle renderHandle) + { + } + + public Task SetParametersAsync(ParameterView parameters) + { + ComponentProperties.SetProperties(parameters, this); + switch (Mode) + { + case "server": + State.RegisterOnPersisting(PersistState, RenderMode.InteractiveServer); + break; + case "wasm": + State.RegisterOnPersisting(PersistState, RenderMode.InteractiveWebAssembly); + break; + case "auto": + State.RegisterOnPersisting(PersistState, RenderMode.InteractiveAuto); + break; + default: + State.RegisterOnPersisting(PersistState); + break; + } + return Task.CompletedTask; + } + } + private static string HtmlContentToString(IHtmlAsyncContent result) { var writer = new StringWriter(); diff --git a/src/Components/Server/src/Circuits/CircuitFactory.cs b/src/Components/Server/src/Circuits/CircuitFactory.cs index 7fce7503f35b..be600dc4db1e 100644 --- a/src/Components/Server/src/Circuits/CircuitFactory.cs +++ b/src/Components/Server/src/Circuits/CircuitFactory.cs @@ -61,8 +61,14 @@ public async ValueTask CreateCircuitHostAsync( navigationManager.Initialize(baseUri, uri); } - var appLifetime = scope.ServiceProvider.GetRequiredService(); - await appLifetime.RestoreStateAsync(store); + if (components.Count > 0) + { + // Skip initializing the state if there are no components. + // This is the case on Blazor Web scenarios, which will initialize the state + // when the first set of components is provided via an UpdateRootComponents call. + var appLifetime = scope.ServiceProvider.GetRequiredService(); + await appLifetime.RestoreStateAsync(store); + } var serverComponentDeserializer = scope.ServiceProvider.GetRequiredService(); var jsComponentInterop = new CircuitJSComponentInterop(_options); @@ -76,7 +82,11 @@ public async ValueTask CreateCircuitHostAsync( jsRuntime, jsComponentInterop); - var circuitHandlers = scope.ServiceProvider.GetServices() + // In Blazor Server we have already restored the app state, so we can get the handlers from DI. + // In Blazor Web the state is provided in the first call to UpdateRootComponents, so we need to + // delay creating the handlers until then. Otherwise, a handler would be able to access the state + // in the constructor for Blazor Server, but not in Blazor Web. + var circuitHandlers = components.Count == 0 ? [] : scope.ServiceProvider.GetServices() .OrderBy(h => h.Order) .ToArray(); diff --git a/src/Components/Server/src/Circuits/CircuitHost.cs b/src/Components/Server/src/Circuits/CircuitHost.cs index 145d4b529b50..313636d3f624 100644 --- a/src/Components/Server/src/Circuits/CircuitHost.cs +++ b/src/Components/Server/src/Circuits/CircuitHost.cs @@ -2,8 +2,10 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Globalization; +using System.Linq; using System.Security.Claims; using Microsoft.AspNetCore.Components.Authorization; +using Microsoft.AspNetCore.Components.Infrastructure; using Microsoft.AspNetCore.SignalR; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; @@ -18,11 +20,12 @@ internal partial class CircuitHost : IAsyncDisposable { private readonly AsyncServiceScope _scope; private readonly CircuitOptions _options; - private readonly CircuitHandler[] _circuitHandlers; private readonly RemoteNavigationManager _navigationManager; private readonly ILogger _logger; private readonly Func, Task> _dispatchInboundActivity; + private CircuitHandler[] _circuitHandlers; private bool _initialized; + private bool _isFirstUpdate = true; private bool _disposed; // This event is fired when there's an unrecoverable exception coming from the circuit, and @@ -111,8 +114,15 @@ public Task InitializeAsync(ProtectedPrerenderComponentApplicationStore store, C { _initialized = true; // We're ready to accept incoming JSInterop calls from here on - await OnCircuitOpenedAsync(cancellationToken); - await OnConnectionUpAsync(cancellationToken); + // We only run the handlers in case we are in a Blazor Server scenario, which renders + // the components inmediately during start. + // On Blazor Web scenarios we delay running these handlers until the first UpdateRootComponents call + // We do this so that the handlers can have access to the restored application state. + if (Descriptors.Count > 0) + { + await OnCircuitOpenedAsync(cancellationToken); + await OnConnectionUpAsync(cancellationToken); + } // Here, we add each root component but don't await the returned tasks so that the // components can be processed in parallel. @@ -130,7 +140,20 @@ public Task InitializeAsync(ProtectedPrerenderComponentApplicationStore store, C // At this point all components have successfully produced an initial render and we can clear the contents of the component // application state store. This ensures the memory that was not used during the initial render of these components gets // reclaimed since no-one else is holding on to it any longer. - store.ExistingState.Clear(); + // This is also important because otherwise components will keep reusing the existing state after + // the initial render instead of initializing their state from the original sources like the Db or a + // web service, preventing UI updates. + if (Descriptors.Count > 0) + { + store.ExistingState.Clear(); + } + + // This variable is used to track that this is the first time we are updating components. + // In Blazor Web scenarios the app will send an initial empty list of descriptors, + // so we want to make sure that we allow setting up the state in that case. + // In Blazor Server the initial set of descriptors is provided via the call to Start, so + // we want to make sure we don't take any state afterwards. + _isFirstUpdate = Descriptors.Count == 0; Log.InitializationSucceeded(_logger); } @@ -702,6 +725,113 @@ private async Task TryNotifyClientErrorAsync(IClientProxy client, string error, } } + internal Task UpdateRootComponents( + (RootComponentOperation, ComponentDescriptor?)[] operations, + ProtectedPrerenderComponentApplicationStore store, + IServerComponentDeserializer serverComponentDeserializer, + CancellationToken cancellation) + { + Log.UpdateRootComponentsStarted(_logger); + + return Renderer.Dispatcher.InvokeAsync(async () => + { + var shouldClearStore = false; + Task[]? pendingTasks = null; + try + { + if (Descriptors.Count > 0) + { + // Block updating components if they were provided during StartCircuit. This keeps + // the footprint for Blazor Server closer to what it was before. + throw new InvalidOperationException("UpdateRootComponents is not supported when components have" + + " been provided during circuit start up."); + } + if (_isFirstUpdate) + { + _isFirstUpdate = false; + if (store != null) + { + shouldClearStore = true; + // We only do this if we have no root components. Otherwise, the state would have been + // provided during the start up process + var appLifetime = _scope.ServiceProvider.GetRequiredService(); + await appLifetime.RestoreStateAsync(store); + } + + // Retrieve the circuit handlers at this point. + _circuitHandlers = [.. _scope.ServiceProvider.GetServices().OrderBy(h => h.Order)]; + await OnCircuitOpenedAsync(cancellation); + await OnConnectionUpAsync(cancellation); + + for (var i = 0; i < operations.Length; i++) + { + var operation = operations[i]; + if (operation.Item1.Type != RootComponentOperationType.Add) + { + throw new InvalidOperationException($"The first set of update operations must always be of type {nameof(RootComponentOperationType.Add)}"); + } + } + + pendingTasks = new Task[operations.Length]; + } + + for (var i = 0; i < operations.Length;i++) + { + var (operation, descriptor) = operations[i]; + switch (operation.Type) + { + case RootComponentOperationType.Add: + var task = Renderer.AddComponentAsync(descriptor.ComponentType, descriptor.Parameters, operation.SelectorId.Value.ToString(CultureInfo.InvariantCulture)); + if (pendingTasks != null) + { + pendingTasks[i] = task; + } + break; + case RootComponentOperationType.Update: + var componentType = Renderer.GetExistingComponentType(operation.ComponentId.Value); + if (descriptor.ComponentType != componentType) + { + Log.InvalidComponentTypeForUpdate(_logger, message: "Component type mismatch."); + throw new InvalidOperationException($"Incorrect type for descriptor '{descriptor.ComponentType.FullName}'"); + } + + // We don't need to await component updates as any unhandled exception will be reported and terminate the circuit. + _ = Renderer.UpdateRootComponentAsync(operation.ComponentId.Value, descriptor.Parameters); + + break; + case RootComponentOperationType.Remove: + Renderer.RemoveExistingRootComponent(operation.ComponentId.Value); + break; + } + } + + if (pendingTasks != null) + { + await Task.WhenAll(pendingTasks); + } + + Log.UpdateRootComponentsSucceeded(_logger); + } + catch (Exception ex) + { + // Report errors asynchronously. UpdateRootComponents is designed not to throw. + Log.UpdateRootComponentsFailed(_logger, ex); + UnhandledException?.Invoke(this, new UnhandledExceptionEventArgs(ex, isTerminating: false)); + await TryNotifyClientErrorAsync(Client, GetClientErrorMessage(ex), ex); + } + finally + { + if (shouldClearStore) + { + // At this point all components have successfully produced an initial render and we can clear the contents of the component + // application state store. This ensures the memory that was not used during the initial render of these components gets + // reclaimed since no-one else is holding on to it any longer. + store.ExistingState.Clear(); + } + } + }); + } + private static partial class Log { // 100s used for lifecycle stuff @@ -740,6 +870,15 @@ private static partial class Log [LoggerMessage(110, LogLevel.Error, "Unhandled error invoking circuit handler type {handlerType}.{handlerMethod}: {Message}", EventName = "CircuitHandlerFailed")] private static partial void CircuitHandlerFailed(ILogger logger, Type handlerType, string handlerMethod, string message, Exception exception); + [LoggerMessage(111, LogLevel.Debug, "Update root components started.", EventName = nameof(UpdateRootComponentsStarted))] + public static partial void UpdateRootComponentsStarted(ILogger logger); + + [LoggerMessage(112, LogLevel.Debug, "Update root components succeeded.", EventName = nameof(UpdateRootComponentsSucceeded))] + public static partial void UpdateRootComponentsSucceeded(ILogger logger); + + [LoggerMessage(113, LogLevel.Debug, "Update root components failed.", EventName = nameof(UpdateRootComponentsFailed))] + public static partial void UpdateRootComponentsFailed(ILogger logger, Exception exception); + public static void CircuitHandlerFailed(ILogger logger, CircuitHandler handler, string handlerMethod, Exception exception) { CircuitHandlerFailed( @@ -765,6 +904,9 @@ public static void CircuitHandlerFailed(ILogger logger, CircuitHandler handler, [LoggerMessage(115, LogLevel.Debug, "An exception occurred on the circuit host '{CircuitId}' while the client is disconnected.", EventName = "UnhandledExceptionClientDisconnected")] public static partial void UnhandledExceptionClientDisconnected(ILogger logger, CircuitId circuitId, Exception exception); + [LoggerMessage(116, LogLevel.Debug, "The root component operation of type 'Update' was invalid: {Message}", EventName = nameof(InvalidComponentTypeForUpdate))] + public static partial void InvalidComponentTypeForUpdate(ILogger logger, string message); + [LoggerMessage(200, LogLevel.Debug, "Failed to parse the event data when trying to dispatch an event.", EventName = "DispatchEventFailedToParseEventData")] public static partial void DispatchEventFailedToParseEventData(ILogger logger, Exception ex); diff --git a/src/Components/Server/src/Circuits/IServerComponentDeserializer.cs b/src/Components/Server/src/Circuits/IServerComponentDeserializer.cs index aa13fbb78fa8..0959a6925701 100644 --- a/src/Components/Server/src/Circuits/IServerComponentDeserializer.cs +++ b/src/Components/Server/src/Circuits/IServerComponentDeserializer.cs @@ -10,6 +10,6 @@ internal interface IServerComponentDeserializer bool TryDeserializeComponentDescriptorCollection( string serializedComponentRecords, out List descriptors); - bool TryDeserializeSingleComponentDescriptor(ComponentMarker record, [NotNullWhen(true)] out ComponentDescriptor? result); + bool TryDeserializeRootComponentOperations(string serializedComponentOperations, out (RootComponentOperation, ComponentDescriptor?)[] operationsWithDescriptors); } diff --git a/src/Components/Server/src/Circuits/RemoteRenderer.cs b/src/Components/Server/src/Circuits/RemoteRenderer.cs index 40f2f7a87a4c..48eb9df03b8e 100644 --- a/src/Components/Server/src/Circuits/RemoteRenderer.cs +++ b/src/Components/Server/src/Circuits/RemoteRenderer.cs @@ -3,9 +3,7 @@ using System.Collections.Concurrent; using System.Diagnostics.CodeAnalysis; -using System.Globalization; using System.Linq; -using System.Text.Json; using Microsoft.AspNetCore.Components.RenderTree; using Microsoft.AspNetCore.Components.Web; using Microsoft.AspNetCore.SignalR; @@ -72,93 +70,14 @@ protected override void AttachRootComponentToBrowser(int componentId, string dom _ = CaptureAsyncExceptions(attachComponentTask); } - protected override void UpdateRootComponents(string operationsJson) - { - var operations = JsonSerializer.Deserialize>( - operationsJson, - ServerComponentSerializationSettings.JsonSerializationOptions); - - foreach (var operation in operations) - { - switch (operation.Type) - { - case RootComponentOperationType.Add: - AddRootComponent(operation); - break; - case RootComponentOperationType.Update: - UpdateRootComponent(operation); - break; - case RootComponentOperationType.Remove: - RemoveRootComponent(operation); - break; - } - } - - return; - - void AddRootComponent(RootComponentOperation operation) - { - if (operation.SelectorId is not { } selectorId) - { - Log.InvalidRootComponentOperation(_logger, operation.Type, message: "Missing selector ID."); - return; - } + internal Task UpdateRootComponentAsync(int componentId, ParameterView initialParameters) => + RenderRootComponentAsync(componentId, initialParameters); - if (operation.Marker is not { } marker) - { - Log.InvalidRootComponentOperation(_logger, operation.Type, message: "Missing marker."); - return; - } - - if (!_serverComponentDeserializer.TryDeserializeSingleComponentDescriptor(marker, out var descriptor)) - { - throw new InvalidOperationException("Failed to deserialize a component descriptor when adding a new root component."); - } + internal void RemoveExistingRootComponent(int componentId) => + RemoveRootComponent(componentId); - _ = AddComponentAsync(descriptor.ComponentType, descriptor.Parameters, selectorId.ToString(CultureInfo.InvariantCulture)); - } - - void UpdateRootComponent(RootComponentOperation operation) - { - if (operation.ComponentId is not { } componentId) - { - Log.InvalidRootComponentOperation(_logger, operation.Type, message: "Missing component ID."); - return; - } - - if (operation.Marker is not { } marker) - { - Log.InvalidRootComponentOperation(_logger, operation.Type, message: "Missing marker."); - return; - } - - var componentState = GetComponentState(componentId); - - if (!_serverComponentDeserializer.TryDeserializeSingleComponentDescriptor(marker, out var descriptor)) - { - throw new InvalidOperationException("Failed to deserialize a component descriptor when updating an existing root component."); - } - - if (descriptor.ComponentType != componentState.Component.GetType()) - { - Log.InvalidRootComponentOperation(_logger, operation.Type, message: "Component type mismatch."); - return; - } - - _ = RenderRootComponentAsync(componentId, descriptor.Parameters); - } - - void RemoveRootComponent(RootComponentOperation operation) - { - if (operation.ComponentId is not { } componentId) - { - Log.InvalidRootComponentOperation(_logger, operation.Type, message: "Missing component ID."); - return; - } - - this.RemoveRootComponent(componentId); - } - } + internal Type GetExistingComponentType(int componentId) => + GetComponentState(componentId).Component.GetType(); protected override void ProcessPendingRender() { @@ -483,9 +402,6 @@ public static void CompletingBatchWithoutError(ILogger logger, long batchId, Tim [LoggerMessage(107, LogLevel.Debug, "The queue of unacknowledged render batches is full.", EventName = "FullUnacknowledgedRenderBatchesQueue")] public static partial void FullUnacknowledgedRenderBatchesQueue(ILogger logger); - - [LoggerMessage(108, LogLevel.Debug, "The root component operation of type '{OperationType}' was invalid: {Message}", EventName = "InvalidRootComponentOperation")] - public static partial void InvalidRootComponentOperation(ILogger logger, RootComponentOperationType operationType, string message); } } diff --git a/src/Components/Server/src/Circuits/ServerComponentDeserializer.cs b/src/Components/Server/src/Circuits/ServerComponentDeserializer.cs index 36607d12ae58..bea61cedf912 100644 --- a/src/Components/Server/src/Circuits/ServerComponentDeserializer.cs +++ b/src/Components/Server/src/Circuits/ServerComponentDeserializer.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using System.Buffers; using System.Diagnostics.CodeAnalysis; using System.Text; using System.Text.Json; @@ -270,6 +271,95 @@ private bool IsWellFormedServerComponent(ComponentMarker record) return (componentDescriptor, serverComponent); } + public bool TryDeserializeRootComponentOperations(string serializedComponentOperations, out (RootComponentOperation, ComponentDescriptor?)[] operations) + { + int[]? seenComponentIdsStorage = null; + try + { + var result = JsonSerializer.Deserialize( + serializedComponentOperations, + ServerComponentSerializationSettings.JsonSerializationOptions); + + operations = new (RootComponentOperation, ComponentDescriptor?)[result.Length]; + + Span seenComponentIds = result.Length <= 128 + ? stackalloc int[result.Length] + : (seenComponentIdsStorage = ArrayPool.Shared.Rent(result.Length)).AsSpan(0, result.Length); + var currentComponentIdIndex = 0; + for (var i = 0; i < result.Length; i++) + { + var operation = result[i]; + if (operation.Type == RootComponentOperationType.Remove || + operation.Type == RootComponentOperationType.Update) + { + if (operation.ComponentId == null) + { + Log.InvalidRootComponentOperation(_logger, operation.Type, message: "Missing component ID."); + operations = null; + return false; + } + + if (seenComponentIds[0..currentComponentIdIndex] + .Contains(operation.ComponentId.Value)) + { + Log.InvalidRootComponentOperation(_logger, operation.Type, message: "Duplicate component ID."); + operations = null; + return false; + } + + seenComponentIds[currentComponentIdIndex++] = operation.ComponentId.Value; + } + + if (operation.Type == RootComponentOperationType.Remove) + { + operations[i] = (operation, null); + continue; + } + + if (operation.Type == RootComponentOperationType.Add) + { + if (operation.SelectorId is not { } selectorId) + { + Log.InvalidRootComponentOperation(_logger, operation.Type, message: "Missing selector ID."); + operations = null; + return false; + } + } + + if (operation.Marker == null) + { + Log.InvalidRootComponentOperation(_logger, operation.Type, message: "Missing marker."); + operations = null; + return false; + } + + if (!TryDeserializeSingleComponentDescriptor(operation.Marker.Value, out var descriptor)) + { + operations = null; + return false; + } + + operations[i] = (operation, descriptor); + } + + return true; + + } + catch (Exception ex) + { + Log.FailedToProcessRootComponentOperations(_logger, ex); + operations = null; + return false; + } + finally + { + if (seenComponentIdsStorage != null) + { + ArrayPool.Shared.Return(seenComponentIdsStorage); + } + } + } + private static partial class Log { [LoggerMessage(1, LogLevel.Debug, "Failed to deserialize the component descriptor.", EventName = "FailedToDeserializeDescriptor")] @@ -301,5 +391,11 @@ private static partial class Log [LoggerMessage(10, LogLevel.Debug, "The descriptor with sequence '{sequence}' was already used for the current invocationId '{invocationId}'.", EventName = "ReusedDescriptorSequence")] public static partial void ReusedDescriptorSequence(ILogger logger, int sequence, string invocationId); + + [LoggerMessage(11, LogLevel.Debug, "The root component operation of type '{OperationType}' was invalid: {Message}", EventName = "InvalidRootComponentOperation")] + public static partial void InvalidRootComponentOperation(ILogger logger, RootComponentOperationType operationType, string message); + + [LoggerMessage(12, LogLevel.Debug, "Failed to parse root component operations", EventName = nameof(FailedToProcessRootComponentOperations))] + public static partial void FailedToProcessRootComponentOperations(ILogger logger, Exception exception); } } diff --git a/src/Components/Server/src/ComponentHub.cs b/src/Components/Server/src/ComponentHub.cs index ecfda9e35f65..730e75b71ddf 100644 --- a/src/Components/Server/src/ComponentHub.cs +++ b/src/Components/Server/src/ComponentHub.cs @@ -160,6 +160,33 @@ public async ValueTask StartCircuit(string baseUri, string uri, string s } } + public async Task UpdateRootComponents(string serializedComponentOperations, string applicationState) + { + var circuitHost = await GetActiveCircuitAsync(); + if (circuitHost == null) + { + return; + } + + if (!_serverComponentSerializer.TryDeserializeRootComponentOperations( + serializedComponentOperations, + out var operations)) + { + // There was an error, so kill the circuit. + await _circuitRegistry.TerminateAsync(circuitHost.CircuitId); + await NotifyClientError(Clients.Caller, "The list of component operations is not valid."); + Context.Abort(); + + return; + } + + var store = !string.IsNullOrEmpty(applicationState) ? + new ProtectedPrerenderComponentApplicationStore(applicationState, _dataProtectionProvider) : + new ProtectedPrerenderComponentApplicationStore(_dataProtectionProvider); + + _ = circuitHost.UpdateRootComponents(operations, store, _serverComponentSerializer, Context.ConnectionAborted); + } + public async ValueTask ConnectCircuit(string circuitIdSecret) { // TryParseCircuitId will not throw. diff --git a/src/Components/Server/test/Circuits/CircuitHostTest.cs b/src/Components/Server/test/Circuits/CircuitHostTest.cs index fd8e82909726..dc1a53879884 100644 --- a/src/Components/Server/test/Circuits/CircuitHostTest.cs +++ b/src/Components/Server/test/Circuits/CircuitHostTest.cs @@ -3,6 +3,9 @@ using System.Diagnostics.CodeAnalysis; using System.Reflection; +using System.Text.Json; +using Microsoft.AspNetCore.Components.Endpoints; +using Microsoft.AspNetCore.Components.Rendering; using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.SignalR; using Microsoft.Extensions.DependencyInjection; @@ -15,6 +18,9 @@ namespace Microsoft.AspNetCore.Components.Server.Circuits; public class CircuitHostTest { + private readonly IDataProtectionProvider _ephemeralDataProtectionProvider = new EphemeralDataProtectionProvider(); + private readonly ServerComponentInvocationSequence _invocationSequence = new(); + [Fact] public async Task DisposeAsync_DisposesResources() { @@ -252,7 +258,7 @@ public async Task InitializeAsync_ReportsOwnAsyncExceptions() .Returns(tcs.Task) .Verifiable(); - var circuitHost = TestCircuitHost.Create(handlers: new[] { handler.Object }); + var circuitHost = TestCircuitHost.Create(handlers: new[] { handler.Object }, descriptors: [new ComponentDescriptor() ]); circuitHost.UnhandledException += (sender, errorInfo) => { Assert.Same(circuitHost, sender); @@ -405,6 +411,194 @@ await circuitHost.HandleInboundActivityAsync(() => Assert.True(wasHandlerFuncInvoked); } + [Fact] + public async Task UpdateRootComponents_CanAddNewRootComponent() + { + // Arrange + var circuitHost = TestCircuitHost.Create( + remoteRenderer: GetRemoteRenderer(), + serviceScope: new ServiceCollection().BuildServiceProvider().CreateAsyncScope()); + var expectedMessage = "Hello, world!"; + Dictionary parameters = new() + { + [nameof(DynamicallyAddedComponent.Message)] = expectedMessage, + }; + var operation = new RootComponentOperation + { + Type = RootComponentOperationType.Add, + SelectorId = 1, + Marker = CreateMarker(typeof(DynamicallyAddedComponent), parameters), + }; + var descriptor = new ComponentDescriptor() + { + ComponentType = typeof(DynamicallyAddedComponent), + Parameters = ParameterView.FromDictionary(parameters), + Sequence = 0, + }; + + // Act + await circuitHost.UpdateRootComponents( + [(operation, descriptor)], null, CreateDeserializer(), CancellationToken.None); + + // Assert + var componentState = ((TestRemoteRenderer)circuitHost.Renderer).GetTestComponentState(0); + var component = Assert.IsType(componentState.Component); + Assert.Equal(expectedMessage, component.Message); + } + + [Fact] + public async Task UpdateRootComponents_CanUpdateExistingRootComponent() + { + // Arrange + var circuitHost = TestCircuitHost.Create( + remoteRenderer: GetRemoteRenderer(), + serviceScope: new ServiceCollection().BuildServiceProvider().CreateAsyncScope()); + var expectedMessage = "Updated message"; + + Dictionary parameters = new() + { + [nameof(DynamicallyAddedComponent.Message)] = expectedMessage, + }; + await AddComponent(circuitHost, parameters); + + var operation = new RootComponentOperation + { + Type = RootComponentOperationType.Update, + ComponentId = 0, + Marker = CreateMarker(typeof(DynamicallyAddedComponent), new() + { + [nameof(DynamicallyAddedComponent.Message)] = expectedMessage, + }), + }; + var descriptor = new ComponentDescriptor() + { + ComponentType = typeof(DynamicallyAddedComponent), + Parameters = ParameterView.FromDictionary(new Dictionary()), + Sequence = 0, + }; + + // Act + await circuitHost.UpdateRootComponents([(operation, descriptor)], null, CreateDeserializer(), CancellationToken.None); + + // Assert + var componentState = ((TestRemoteRenderer)circuitHost.Renderer).GetTestComponentState(0); + var component = Assert.IsType(componentState.Component); + Assert.Equal(expectedMessage, component.Message); + } + + [Fact] + public async Task UpdateRootComponents_DoesNotUpdateExistingRootComponent_WhenDescriptorComponentTypeDoesNotMatchRootComponentType() + { + // Arrange + var circuitHost = TestCircuitHost.Create( + remoteRenderer: GetRemoteRenderer(), + serviceScope: new ServiceCollection().BuildServiceProvider().CreateAsyncScope()); + + // Arrange + var expectedMessage = "Existing message"; + await AddComponent(circuitHost, new Dictionary() + { + [nameof(DynamicallyAddedComponent.Message)] = expectedMessage, + }); + + await AddComponent(circuitHost, []); + + Dictionary parameters = new() + { + [nameof(DynamicallyAddedComponent.Message)] = "Updated message", + }; + var operation = new RootComponentOperation + { + Type = RootComponentOperationType.Update, + ComponentId = 0, + Marker = CreateMarker(typeof(TestComponent) /* Note the incorrect component type */, parameters), + }; + var descriptor = new ComponentDescriptor() + { + ComponentType = typeof(TestComponent), + Parameters = ParameterView.FromDictionary(parameters), + Sequence = 0, + }; + var operationsJson = JsonSerializer.Serialize( + new[] { operation }, + ServerComponentSerializationSettings.JsonSerializationOptions); + + // Act + var evt = Assert.Raises( + handler => circuitHost.UnhandledException += new UnhandledExceptionEventHandler(handler), + handler => circuitHost.UnhandledException -= new UnhandledExceptionEventHandler(handler), + () => circuitHost.UpdateRootComponents( + [(operation, descriptor)], null, CreateDeserializer(), CancellationToken.None)); + + // Assert + var componentState = ((TestRemoteRenderer)circuitHost.Renderer).GetTestComponentState(0); + var component = Assert.IsType(componentState.Component); + Assert.Equal(expectedMessage, component.Message); + + Assert.NotNull(evt); + var exception = Assert.IsType(evt.Arguments.ExceptionObject); + } + + [Fact] + public async Task UpdateRootComponents_CanRemoveExistingRootComponent() + { + // Arrange + var circuitHost = TestCircuitHost.Create( + remoteRenderer: GetRemoteRenderer(), + serviceScope: new ServiceCollection().BuildServiceProvider().CreateAsyncScope()); + var expectedMessage = "Updated message"; + + Dictionary parameters = new() + { + [nameof(DynamicallyAddedComponent.Message)] = expectedMessage, + }; + await AddComponent(circuitHost, parameters); + + var operation = new RootComponentOperation + { + Type = RootComponentOperationType.Remove, + ComponentId = 0, + }; + + // Act + await circuitHost.UpdateRootComponents([(operation, null)], null, CreateDeserializer(), CancellationToken.None); + + // Assert + Assert.Throws(() => + ((TestRemoteRenderer)circuitHost.Renderer).GetTestComponentState(0)); + } + + private async Task AddComponent(CircuitHost circuitHost, Dictionary parameters) + where TComponent : IComponent + { + var addOperation = new RootComponentOperation + { + Type = RootComponentOperationType.Add, + SelectorId = 1, + Marker = CreateMarker(typeof(TComponent), parameters), + }; + var addDescriptor = new ComponentDescriptor() + { + ComponentType = typeof(TComponent), + Parameters = ParameterView.FromDictionary(parameters), + Sequence = 0, + }; + + // Add component + await circuitHost.UpdateRootComponents( + [(addOperation, addDescriptor)], null, CreateDeserializer(), CancellationToken.None); + } + + private ProtectedPrerenderComponentApplicationStore CreateStore() + { + return new ProtectedPrerenderComponentApplicationStore(_ephemeralDataProtectionProvider); + } + + private ServerComponentDeserializer CreateDeserializer() + { + return new ServerComponentDeserializer(_ephemeralDataProtectionProvider, NullLogger.Instance, new RootComponentTypeCache(), new ComponentParameterDeserializer(NullLogger.Instance, new ComponentParametersTypeCache())); + } + private static TestRemoteRenderer GetRemoteRenderer() { var serviceCollection = new ServiceCollection(); @@ -434,6 +628,18 @@ private static void SetupMockInboundActivityHandler(Mock circuit .Verifiable(); } + private ComponentMarker CreateMarker(Type type, Dictionary parameters = null) + { + var serializer = new ServerComponentSerializer(_ephemeralDataProtectionProvider); + var marker = ComponentMarker.Create(ComponentMarker.ServerMarkerType, false, null); + serializer.SerializeInvocation( + ref marker, + _invocationSequence, + type, + parameters is null ? ParameterView.Empty : ParameterView.FromDictionary(parameters)); + return marker; + } + private class TestRemoteRenderer : RemoteRenderer { public TestRemoteRenderer(IServiceProvider serviceProvider, IClientProxy client) @@ -449,6 +655,9 @@ public TestRemoteRenderer(IServiceProvider serviceProvider, IClientProxy client) { } + public ComponentState GetTestComponentState(int id) + => base.GetComponentState(id); + protected override void Dispose(bool disposing) { base.Dispose(disposing); @@ -580,10 +789,95 @@ public bool TryDeserializeComponentDescriptorCollection(string serializedCompone return true; } + public bool TryDeserializeRootComponentOperations(string serializedComponentOperations, out (RootComponentOperation, ComponentDescriptor)[] operationsWithDescriptors) + { + operationsWithDescriptors= default; + return true; + } + public bool TryDeserializeSingleComponentDescriptor(ComponentMarker record, [NotNullWhen(true)] out ComponentDescriptor result) { result = default; return true; } } + + private class DynamicallyAddedComponent : IComponent, IDisposable + { + private readonly TaskCompletionSource _disposeTcs = new(); + private RenderHandle _renderHandle; + + [Parameter] + public string Message { get; set; } = "Default message"; + + private void Render(RenderTreeBuilder builder) + { + builder.AddContent(0, Message); + } + + public void Attach(RenderHandle renderHandle) + { + _renderHandle = renderHandle; + } + + public Task SetParametersAsync(ParameterView parameters) + { + if (parameters.TryGetValue(nameof(Message), out var message)) + { + Message = message; + } + + TriggerRender(); + return Task.CompletedTask; + } + + public void TriggerRender() + { + var task = _renderHandle.Dispatcher.InvokeAsync(() => _renderHandle.Render(Render)); + Assert.True(task.IsCompletedSuccessfully); + } + + public Task WaitForDisposeAsync() + => _disposeTcs.Task; + + public void Dispose() + { + _disposeTcs.SetResult(); + } + } + + private class TestComponent() : IComponent, IHandleAfterRender + { + private RenderHandle _renderHandle; + private readonly RenderFragment _renderFragment = (builder) => + { + builder.OpenElement(0, "my element"); + builder.AddContent(1, "some text"); + builder.CloseElement(); + }; + + public TestComponent(RenderFragment renderFragment) : this() => _renderFragment = renderFragment; + + public Action OnAfterRenderComplete { get; set; } + + public void Attach(RenderHandle renderHandle) => _renderHandle = renderHandle; + + public Task OnAfterRenderAsync() + { + OnAfterRenderComplete?.Invoke(); + return Task.CompletedTask; + } + + public Task SetParametersAsync(ParameterView parameters) + { + TriggerRender(); + return Task.CompletedTask; + } + + public void TriggerRender() + { + var task = _renderHandle.Dispatcher.InvokeAsync(() => _renderHandle.Render(_renderFragment)); + Assert.True(task.IsCompletedSuccessfully); + } + } } diff --git a/src/Components/Server/test/Circuits/ComponentHubTest.cs b/src/Components/Server/test/Circuits/ComponentHubTest.cs index 263ff8c4860f..afdc33e7e674 100644 --- a/src/Components/Server/test/Circuits/ComponentHubTest.cs +++ b/src/Components/Server/test/Circuits/ComponentHubTest.cs @@ -170,6 +170,12 @@ public bool TryDeserializeComponentDescriptorCollection(string serializedCompone return true; } + public bool TryDeserializeRootComponentOperations(string serializedComponentOperations, out (RootComponentOperation, ComponentDescriptor)[] operationsWithDescriptors) + { + operationsWithDescriptors = default; + return true; + } + public bool TryDeserializeSingleComponentDescriptor(ComponentMarker record, [NotNullWhen(true)] out ComponentDescriptor result) { result = default; diff --git a/src/Components/Server/test/Circuits/RemoteRendererTest.cs b/src/Components/Server/test/Circuits/RemoteRendererTest.cs index ae0dd4247fc1..5a0f8686c689 100644 --- a/src/Components/Server/test/Circuits/RemoteRendererTest.cs +++ b/src/Components/Server/test/Circuits/RemoteRendererTest.cs @@ -25,7 +25,6 @@ public class RemoteRendererTest private static readonly TimeSpan Timeout = Debugger.IsAttached ? System.Threading.Timeout.InfiniteTimeSpan : TimeSpan.FromSeconds(10); private readonly IDataProtectionProvider _ephemeralDataProtectionProvider = new EphemeralDataProtectionProvider(); - private readonly ServerComponentInvocationSequence _invocationSequence = new(); [Fact] public void WritesAreBufferedWhenTheClientIsOffline() @@ -426,239 +425,6 @@ await renderer.Dispatcher.InvokeAsync(() => renderer.RenderComponentAsync renderer.UpdateRootComponents(operationsJson)); - var componentState = renderer.GetComponentState(0); - - // Assert - var component = Assert.IsType(componentState.Component); - Assert.Equal(expectedMessage, component.Message); - } - - [Fact] - public async Task UpdateRootComponents_DoesNotAddNewRootComponent_WhenSelectorIdIsMissing() - { - // Arrange - var serviceProvider = CreateServiceProvider(); - var renderer = GetRemoteRenderer(serviceProvider); - var operation = new RootComponentOperation - { - Type = RootComponentOperationType.Add, - Marker = CreateMarker(typeof(DynamicallyAddedComponent)), - }; - var operationsJson = JsonSerializer.Serialize( - new[] { operation }, - ServerComponentSerializationSettings.JsonSerializationOptions); - - // Act - await renderer.Dispatcher.InvokeAsync(() => renderer.UpdateRootComponents(operationsJson)); - renderer.UpdateRootComponents(operationsJson); - - // Assert - var ex = Assert.Throws(() => renderer.GetComponentState(0)); - Assert.StartsWith("The renderer does not have a component with ID", ex.Message); - } - - [Fact] - public async Task UpdateRootComponents_Throws_WhenAddingComponentFromInvalidDescriptor() - { - // Arrange - var serviceProvider = CreateServiceProvider(); - var renderer = GetRemoteRenderer(serviceProvider); - var operation = new RootComponentOperation - { - Type = RootComponentOperationType.Add, - SelectorId = 1, - Marker = new ComponentMarker() - { - Descriptor = "some random text", - }, - }; - var operationsJson = JsonSerializer.Serialize( - new[] { operation }, - ServerComponentSerializationSettings.JsonSerializationOptions); - - // Act - var task = renderer.Dispatcher.InvokeAsync(() => renderer.UpdateRootComponents(operationsJson)); - - // Assert - var ex = await Assert.ThrowsAsync(async () => await task); - Assert.StartsWith("Failed to deserialize a component descriptor when adding", ex.Message); - } - - [Fact] - public async Task UpdateRootComponents_CanUpdateExistingRootComponent() - { - // Arrange - var serviceProvider = CreateServiceProvider(); - var renderer = GetRemoteRenderer(serviceProvider); - var component = new DynamicallyAddedComponent() - { - Message = "Existing message", - }; - var expectedMessage = "Updated message"; - var componentId = renderer.AssignRootComponentId(component); - var operation = new RootComponentOperation - { - Type = RootComponentOperationType.Update, - ComponentId = componentId, - Marker = CreateMarker(typeof(DynamicallyAddedComponent), new() - { - [nameof(DynamicallyAddedComponent.Message)] = expectedMessage, - }), - }; - var operationsJson = JsonSerializer.Serialize( - new[] { operation }, - ServerComponentSerializationSettings.JsonSerializationOptions); - - // Act - await renderer.Dispatcher.InvokeAsync(() => renderer.UpdateRootComponents(operationsJson)); - - // Assert - Assert.Equal(expectedMessage, component.Message); - } - - [Fact] - public async Task UpdateRootComponents_DoesNotUpdateExistingRootComponent_WhenComponentIdIsMissing() - { - // Arrange - var serviceProvider = CreateServiceProvider(); - var renderer = GetRemoteRenderer(serviceProvider); - var expectedMessage = "Existing message"; - var component = new DynamicallyAddedComponent() - { - Message = expectedMessage, - }; - var componentId = renderer.AssignRootComponentId(component); - var operation = new RootComponentOperation - { - Type = RootComponentOperationType.Update, - Marker = CreateMarker(typeof(DynamicallyAddedComponent), new() - { - [nameof(DynamicallyAddedComponent.Message)] = "Some other message", - }), - }; - var operationsJson = JsonSerializer.Serialize( - new[] { operation }, - ServerComponentSerializationSettings.JsonSerializationOptions); - - // Act - await renderer.Dispatcher.InvokeAsync(() => renderer.UpdateRootComponents(operationsJson)); - - // Assert - Assert.Equal(expectedMessage, component.Message); - } - - [Fact] - public async Task UpdateRootComponents_DoesNotUpdateExistingRootComponent_WhenDescriptorComponentTypeDoesNotMatchRootComponentType() - { - // Arrange - var serviceProvider = CreateServiceProvider(); - var renderer = GetRemoteRenderer(serviceProvider); - var expectedMessage = "Existing message"; - var component1 = new DynamicallyAddedComponent() - { - Message = expectedMessage, - }; - var component2 = new TestComponent(); - var component1Id = renderer.AssignRootComponentId(component1); - var component2Id = renderer.AssignRootComponentId(component2); - var operation = new RootComponentOperation - { - Type = RootComponentOperationType.Update, - ComponentId = component1Id, - Marker = CreateMarker(typeof(TestComponent) /* Note the incorrect component type */, new() - { - [nameof(DynamicallyAddedComponent.Message)] = "Updated message", - }), - }; - var operationsJson = JsonSerializer.Serialize( - new[] { operation }, - ServerComponentSerializationSettings.JsonSerializationOptions); - - // Act - await renderer.Dispatcher.InvokeAsync(() => renderer.UpdateRootComponents(operationsJson)); - - // Assert - Assert.Equal(expectedMessage, component1.Message); - } - - [Fact] - public async Task UpdateRootComponents_Throws_WhenUpdatingComponentFromInvalidDescriptor() - { - // Arrange - var serviceProvider = CreateServiceProvider(); - var renderer = GetRemoteRenderer(serviceProvider); - var component = new DynamicallyAddedComponent() - { - Message = "Existing message", - }; - var componentId = renderer.AssignRootComponentId(component); - var operation = new RootComponentOperation - { - Type = RootComponentOperationType.Update, - ComponentId = componentId, - Marker = new() - { - Descriptor = "some random text", - }, - }; - var operationsJson = JsonSerializer.Serialize( - new[] { operation }, - ServerComponentSerializationSettings.JsonSerializationOptions); - - // Act - var task = renderer.Dispatcher.InvokeAsync(() => renderer.UpdateRootComponents(operationsJson)); - - // Assert - var ex = await Assert.ThrowsAsync(async () => await task); - Assert.StartsWith("Failed to deserialize a component descriptor when updating", ex.Message); - } - - [Fact] - public async Task UpdateRootComponents_CanRemoveExistingRootComponent() - { - // Arrange - var serviceProvider = CreateServiceProvider(); - var renderer = GetRemoteRenderer(serviceProvider); - var component = new DynamicallyAddedComponent(); - var componentId = renderer.AssignRootComponentId(component); - var operation = new RootComponentOperation - { - Type = RootComponentOperationType.Remove, - ComponentId = componentId, - }; - var operationsJson = JsonSerializer.Serialize( - new[] { operation }, - ServerComponentSerializationSettings.JsonSerializationOptions); - - // Act - await renderer.Dispatcher.InvokeAsync(() => renderer.UpdateRootComponents(operationsJson)); - - // Assert - await component.WaitForDisposeAsync().WaitAsync(Timeout); // Will timeout and throw if not disposed - } - private IServiceProvider CreateServiceProvider() { var serviceCollection = new ServiceCollection(); @@ -685,18 +451,6 @@ private TestRemoteRenderer GetRemoteRenderer(IServiceProvider serviceProvider, C NullLogger.Instance); } - private ComponentMarker CreateMarker(Type type, Dictionary parameters = null) - { - var serializer = new ServerComponentSerializer(_ephemeralDataProtectionProvider); - var marker = ComponentMarker.Create(ComponentMarker.ServerMarkerType, false, null); - serializer.SerializeInvocation( - ref marker, - _invocationSequence, - type, - parameters is null ? ParameterView.Empty : ParameterView.FromDictionary(parameters)); - return marker; - } - private class TestRemoteRenderer : RemoteRenderer { public TestRemoteRenderer(IServiceProvider serviceProvider, ILoggerFactory loggerFactory, CircuitOptions options, CircuitClientProxy client, IServerComponentDeserializer serverComponentDeserializer, ILogger logger) @@ -715,11 +469,6 @@ protected override void AttachRootComponentToBrowser(int componentId, string dom { } - public new void UpdateRootComponents(string operationsJson) - { - base.UpdateRootComponents(operationsJson); - } - public new ComponentState GetComponentState(int componentId) { return base.GetComponentState(componentId); @@ -811,48 +560,4 @@ public void TriggerRender() Component.TriggerRender(); } } - - private class DynamicallyAddedComponent : IComponent, IDisposable - { - private readonly TaskCompletionSource _disposeTcs = new(); - private RenderHandle _renderHandle; - - [Parameter] - public string Message { get; set; } = "Default message"; - - private void Render(RenderTreeBuilder builder) - { - builder.AddContent(0, Message); - } - - public void Attach(RenderHandle renderHandle) - { - _renderHandle = renderHandle; - } - - public Task SetParametersAsync(ParameterView parameters) - { - if (parameters.TryGetValue(nameof(Message), out var message)) - { - Message = message; - } - - TriggerRender(); - return Task.CompletedTask; - } - - public void TriggerRender() - { - var task = _renderHandle.Dispatcher.InvokeAsync(() => _renderHandle.Render(Render)); - Assert.True(task.IsCompletedSuccessfully); - } - - public Task WaitForDisposeAsync() - => _disposeTcs.Task; - - public void Dispose() - { - _disposeTcs.SetResult(); - } - } } diff --git a/src/Components/Server/test/Circuits/ServerComponentDeserializerTest.cs b/src/Components/Server/test/Circuits/ServerComponentDeserializerTest.cs index fc3fefc3711f..0a7168017e67 100644 --- a/src/Components/Server/test/Circuits/ServerComponentDeserializerTest.cs +++ b/src/Components/Server/test/Circuits/ServerComponentDeserializerTest.cs @@ -394,6 +394,93 @@ public void TryDeserializeSingleComponentDescriptor_DoesNotParseMarkerFromOldInv Assert.False(serverComponentDeserializer.TryDeserializeSingleComponentDescriptor(firstInvocationMarkers[0], out _)); } + [Fact] + public void UpdateRootComponents_TryDeserializeRootComponentOperationsReturnsFalse_WhenAddOperationIsMissingSelectorId() + { + // Arrange + var operation = new RootComponentOperation + { + Type = RootComponentOperationType.Add, + SelectorId = 1, + Marker = new ComponentMarker() + { + Descriptor = "some random text", + }, + }; + var operationsJson = JsonSerializer.Serialize( + new[] { operation }, + ServerComponentSerializationSettings.JsonSerializationOptions); + var deserializer = CreateServerComponentDeserializer(); + + // Act + var result = deserializer.TryDeserializeRootComponentOperations(operationsJson, out var parsed); + + // Assert + Assert.False(result); + Assert.Null(parsed); + } + + [Fact] + public void UpdateRootComponents_TryDeserializeRootComponentOperationsReturnsFalse_WhenComponentIdIsMissing() + { + // Arrange + var operation = new RootComponentOperation + { + Type = RootComponentOperationType.Update, + Marker = CreateMarker(typeof(DynamicallyAddedComponent), new() + { + ["Message"] = "Some other message", + }), + }; + var operationsJson = JsonSerializer.Serialize( + new[] { operation }, + ServerComponentSerializationSettings.JsonSerializationOptions); + + var deserializer = CreateServerComponentDeserializer(); + + // Act + var result = deserializer.TryDeserializeRootComponentOperations(operationsJson, out var parsed); + + // Assert + Assert.False(result); + Assert.Null(parsed); + } + + [Fact] + public void UpdateRootComponents_TryDeserializeRootComponentOperationsReturnsFalse_WhenComponentIdIsRepeated() + { + // Arrange + var operation = new RootComponentOperation + { + Type = RootComponentOperationType.Update, + ComponentId = 1, + Marker = CreateMarker(typeof(DynamicallyAddedComponent), new() + { + ["Message"] = "Some other message", + }), + }; + + var other = new RootComponentOperation + { + Type = RootComponentOperationType.Remove, + ComponentId = 1, + Marker = CreateMarker(typeof(DynamicallyAddedComponent)), + }; + + var operationsJson = JsonSerializer.Serialize( + new[] { operation, other }, + ServerComponentSerializationSettings.JsonSerializationOptions); + + var deserializer = CreateServerComponentDeserializer(); + + // Act + var result = deserializer.TryDeserializeRootComponentOperations(operationsJson, out var parsed); + + // Assert + Assert.False(result); + Assert.Null(parsed); + } + private string SerializeComponent(string assembly, string type) => JsonSerializer.Serialize( new ServerComponent(0, assembly, type, Array.Empty(), Array.Empty(), Guid.NewGuid()), @@ -411,6 +498,18 @@ private ServerComponentDeserializer CreateServerComponentDeserializer() private string SerializeMarkers(ComponentMarker[] markers) => JsonSerializer.Serialize(markers, ServerComponentSerializationSettings.JsonSerializationOptions); + private ComponentMarker CreateMarker(Type type, Dictionary parameters = null) + { + var serializer = new ServerComponentSerializer(_ephemeralDataProtectionProvider); + var marker = ComponentMarker.Create(ComponentMarker.ServerMarkerType, false, null); + serializer.SerializeInvocation( + ref marker, + _invocationSequence, + type, + parameters is null ? ParameterView.Empty : ParameterView.FromDictionary(parameters)); + return marker; + } + private ComponentMarker[] CreateMarkers(params Type[] types) { var serializer = new ServerComponentSerializer(_ephemeralDataProtectionProvider); @@ -466,4 +565,10 @@ private class TestComponent : IComponent public Task SetParametersAsync(ParameterView parameters) => throw new NotImplementedException(); } + + private class DynamicallyAddedComponent : IComponent + { + public void Attach(RenderHandle renderHandle) => throw new NotImplementedException(); + public Task SetParametersAsync(ParameterView parameters) => throw new NotImplementedException(); + } } diff --git a/src/Components/Shared/src/DefaultAntiforgeryStateProvider.cs b/src/Components/Shared/src/DefaultAntiforgeryStateProvider.cs index 0c8506ba70f7..5901618e473e 100644 --- a/src/Components/Shared/src/DefaultAntiforgeryStateProvider.cs +++ b/src/Components/Shared/src/DefaultAntiforgeryStateProvider.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics.CodeAnalysis; +using Microsoft.AspNetCore.Components.Web; namespace Microsoft.AspNetCore.Components.Forms; @@ -25,7 +26,7 @@ public DefaultAntiforgeryStateProvider(PersistentComponentState state) { state.PersistAsJson(PersistenceKey, _currentToken); return Task.CompletedTask; - }); + }, new InteractiveAutoRenderMode()); state.TryTakeFromJson(PersistenceKey, out _currentToken); } diff --git a/src/Components/Web.JS/dist/Release/blazor.server.js b/src/Components/Web.JS/dist/Release/blazor.server.js index af7f0e4266a3..c2433b821374 100644 --- a/src/Components/Web.JS/dist/Release/blazor.server.js +++ b/src/Components/Web.JS/dist/Release/blazor.server.js @@ -1 +1 @@ -(()=>{var e={778:()=>{},77:()=>{},203:()=>{},200:()=>{},628:()=>{},321:()=>{}},t={};function n(o){var r=t[o];if(void 0!==r)return r.exports;var s=t[o]={exports:{}};return e[o](s,s.exports,n),s.exports}n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),(()=>{"use strict";var e,t,o;!function(e){const t=[],n="__jsObjectId",o="__dotNetObject",r="__byte[]",s="__dotNetStream",i="__jsStreamReferenceLength";let a,c;class l{constructor(e){this._jsObject=e,this._cachedFunctions=new Map}findFunction(e){const t=this._cachedFunctions.get(e);if(t)return t;let n,o=this._jsObject;if(e.split(".").forEach((t=>{if(!(t in o))throw new Error(`Could not find '${e}' ('${t}' was undefined).`);n=o,o=o[t]})),o instanceof Function)return o=o.bind(n),this._cachedFunctions.set(e,o),o;throw new Error(`The value '${e}' is not a function.`)}getWrappedObject(){return this._jsObject}}const h={0:new l(window)};h[0]._cachedFunctions.set("import",(e=>("string"==typeof e&&e.startsWith("./")&&(e=new URL(e.substr(2),document.baseURI).toString()),import(e))));let d,u=1;function p(e){t.push(e)}function f(e){if(e&&"object"==typeof e){h[u]=new l(e);const t={[n]:u};return u++,t}throw new Error(`Cannot create a JSObjectReference from the value '${e}'.`)}function g(e){let t=-1;if(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),e instanceof Blob)t=e.size;else{if(!(e.buffer instanceof ArrayBuffer))throw new Error("Supplied value is not a typed array or blob.");if(void 0===e.byteLength)throw new Error(`Cannot create a JSStreamReference from the value '${e}' as it doesn't have a byteLength.`);t=e.byteLength}const o={[i]:t};try{const t=f(e);o[n]=t[n]}catch(t){throw new Error(`Cannot create a JSStreamReference from the value '${e}'.`)}return o}function m(e,n){c=e;const o=n?JSON.parse(n,((e,n)=>t.reduce(((t,n)=>n(e,t)),n))):null;return c=void 0,o}function v(){if(void 0===a)throw new Error("No call dispatcher has been set.");if(null===a)throw new Error("There are multiple .NET runtimes present, so a default dispatcher could not be resolved. Use DotNetObject to invoke .NET instance methods.");return a}e.attachDispatcher=function(e){const t=new y(e);return void 0===a?a=t:a&&(a=null),t},e.attachReviver=p,e.invokeMethod=function(e,t,...n){return v().invokeDotNetStaticMethod(e,t,...n)},e.invokeMethodAsync=function(e,t,...n){return v().invokeDotNetStaticMethodAsync(e,t,...n)},e.createJSObjectReference=f,e.createJSStreamReference=g,e.disposeJSObjectReference=function(e){const t=e&&e[n];"number"==typeof t&&b(t)},function(e){e[e.Default=0]="Default",e[e.JSObjectReference=1]="JSObjectReference",e[e.JSStreamReference=2]="JSStreamReference",e[e.JSVoidResult=3]="JSVoidResult"}(d=e.JSCallResultType||(e.JSCallResultType={}));class y{constructor(e){this._dotNetCallDispatcher=e,this._byteArraysToBeRevived=new Map,this._pendingDotNetToJSStreams=new Map,this._pendingAsyncCalls={},this._nextAsyncCallId=1}getDotNetCallDispatcher(){return this._dotNetCallDispatcher}invokeJSFromDotNet(e,t,n,o){const r=m(this,t),s=I(_(e,o)(...r||[]),n);return null==s?null:T(this,s)}beginInvokeJSFromDotNet(e,t,n,o,r){const s=new Promise((e=>{const o=m(this,n);e(_(t,r)(...o||[]))}));e&&s.then((t=>T(this,[e,!0,I(t,o)]))).then((t=>this._dotNetCallDispatcher.endInvokeJSFromDotNet(e,!0,t)),(t=>this._dotNetCallDispatcher.endInvokeJSFromDotNet(e,!1,JSON.stringify([e,!1,w(t)]))))}endInvokeDotNetFromJS(e,t,n){const o=t?m(this,n):new Error(n);this.completePendingCall(parseInt(e,10),t,o)}invokeDotNetStaticMethod(e,t,...n){return this.invokeDotNetMethod(e,t,null,n)}invokeDotNetStaticMethodAsync(e,t,...n){return this.invokeDotNetMethodAsync(e,t,null,n)}invokeDotNetMethod(e,t,n,o){if(this._dotNetCallDispatcher.invokeDotNetFromJS){const r=T(this,o),s=this._dotNetCallDispatcher.invokeDotNetFromJS(e,t,n,r);return s?m(this,s):null}throw new Error("The current dispatcher does not support synchronous calls from JS to .NET. Use invokeDotNetMethodAsync instead.")}invokeDotNetMethodAsync(e,t,n,o){if(e&&n)throw new Error(`For instance method calls, assemblyName should be null. Received '${e}'.`);const r=this._nextAsyncCallId++,s=new Promise(((e,t)=>{this._pendingAsyncCalls[r]={resolve:e,reject:t}}));try{const s=T(this,o);this._dotNetCallDispatcher.beginInvokeDotNetFromJS(r,e,t,n,s)}catch(e){this.completePendingCall(r,!1,e)}return s}receiveByteArray(e,t){this._byteArraysToBeRevived.set(e,t)}processByteArray(e){const t=this._byteArraysToBeRevived.get(e);return t?(this._byteArraysToBeRevived.delete(e),t):null}supplyDotNetStream(e,t){if(this._pendingDotNetToJSStreams.has(e)){const n=this._pendingDotNetToJSStreams.get(e);this._pendingDotNetToJSStreams.delete(e),n.resolve(t)}else{const n=new C;n.resolve(t),this._pendingDotNetToJSStreams.set(e,n)}}getDotNetStreamPromise(e){let t;if(this._pendingDotNetToJSStreams.has(e))t=this._pendingDotNetToJSStreams.get(e).streamPromise,this._pendingDotNetToJSStreams.delete(e);else{const n=new C;this._pendingDotNetToJSStreams.set(e,n),t=n.streamPromise}return t}completePendingCall(e,t,n){if(!this._pendingAsyncCalls.hasOwnProperty(e))throw new Error(`There is no pending async call with ID ${e}.`);const o=this._pendingAsyncCalls[e];delete this._pendingAsyncCalls[e],t?o.resolve(n):o.reject(n)}}function w(e){return e instanceof Error?`${e.message}\n${e.stack}`:e?e.toString():"null"}function _(e,t){const n=h[t];if(n)return n.findFunction(e);throw new Error(`JS object instance with ID ${t} does not exist (has it been disposed?).`)}function b(e){delete h[e]}e.findJSFunction=_,e.disposeJSObjectReferenceById=b;class S{constructor(e,t){this._id=e,this._callDispatcher=t}invokeMethod(e,...t){return this._callDispatcher.invokeDotNetMethod(null,e,this._id,t)}invokeMethodAsync(e,...t){return this._callDispatcher.invokeDotNetMethodAsync(null,e,this._id,t)}dispose(){this._callDispatcher.invokeDotNetMethodAsync(null,"__Dispose",this._id,null).catch((e=>console.error(e)))}serializeAsArg(){return{[o]:this._id}}}e.DotNetObject=S,p((function(e,t){if(t&&"object"==typeof t){if(t.hasOwnProperty(o))return new S(t[o],c);if(t.hasOwnProperty(n)){const e=t[n],o=h[e];if(o)return o.getWrappedObject();throw new Error(`JS object instance with Id '${e}' does not exist. It may have been disposed.`)}if(t.hasOwnProperty(r)){const e=t[r],n=c.processByteArray(e);if(void 0===n)throw new Error(`Byte array index '${e}' does not exist.`);return n}if(t.hasOwnProperty(s)){const e=t[s],n=c.getDotNetStreamPromise(e);return new E(n)}}return t}));class E{constructor(e){this._streamPromise=e}stream(){return this._streamPromise}async arrayBuffer(){return new Response(await this.stream()).arrayBuffer()}}class C{constructor(){this.streamPromise=new Promise(((e,t)=>{this.resolve=e,this.reject=t}))}}function I(e,t){switch(t){case d.Default:return e;case d.JSObjectReference:return f(e);case d.JSStreamReference:return g(e);case d.JSVoidResult:return null;default:throw new Error(`Invalid JS call result type '${t}'.`)}}let k=0;function T(e,t){k=0,c=e;const n=JSON.stringify(t,D);return c=void 0,n}function D(e,t){if(t instanceof S)return t.serializeAsArg();if(t instanceof Uint8Array){c.getDotNetCallDispatcher().sendByteArray(k,t);const e={[r]:k};return k++,e}return t}}(e||(e={})),function(e){e[e.prependFrame=1]="prependFrame",e[e.removeFrame=2]="removeFrame",e[e.setAttribute=3]="setAttribute",e[e.removeAttribute=4]="removeAttribute",e[e.updateText=5]="updateText",e[e.stepIn=6]="stepIn",e[e.stepOut=7]="stepOut",e[e.updateMarkup=8]="updateMarkup",e[e.permutationListEntry=9]="permutationListEntry",e[e.permutationListEnd=10]="permutationListEnd"}(t||(t={})),function(e){e[e.element=1]="element",e[e.text=2]="text",e[e.attribute=3]="attribute",e[e.component=4]="component",e[e.region=5]="region",e[e.elementReferenceCapture=6]="elementReferenceCapture",e[e.markup=8]="markup",e[e.namedEvent=10]="namedEvent"}(o||(o={}));class r{constructor(e,t){this.componentId=e,this.fieldValue=t}static fromEvent(e,t){const n=t.target;if(n instanceof Element){const t=function(e){return e instanceof HTMLInputElement?e.type&&"checkbox"===e.type.toLowerCase()?{value:e.checked}:{value:e.value}:e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement?{value:e.value}:null}(n);if(t)return new r(e,t.value)}return null}}const s=new Map,i=new Map,a=[];function c(e){return s.get(e)}function l(e){const t=s.get(e);return(null==t?void 0:t.browserEventName)||e}function h(e,t){e.forEach((e=>s.set(e,t)))}function d(e){const t=[];for(let n=0;ne.selected)).map((e=>e.value))}}{const e=function(e){return!!e&&"INPUT"===e.tagName&&"checkbox"===e.getAttribute("type")}(t);return{value:e?!!t.checked:t.value}}}}),h(["copy","cut","paste"],{createEventArgs:e=>({type:e.type})}),h(["drag","dragend","dragenter","dragleave","dragover","dragstart","drop"],{createEventArgs:e=>{return{...u(t=e),dataTransfer:t.dataTransfer?{dropEffect:t.dataTransfer.dropEffect,effectAllowed:t.dataTransfer.effectAllowed,files:Array.from(t.dataTransfer.files).map((e=>e.name)),items:Array.from(t.dataTransfer.items).map((e=>({kind:e.kind,type:e.type}))),types:t.dataTransfer.types}:null};var t}}),h(["focus","blur","focusin","focusout"],{createEventArgs:e=>({type:e.type})}),h(["keydown","keyup","keypress"],{createEventArgs:e=>{return{key:(t=e).key,code:t.code,location:t.location,repeat:t.repeat,ctrlKey:t.ctrlKey,shiftKey:t.shiftKey,altKey:t.altKey,metaKey:t.metaKey,type:t.type};var t}}),h(["contextmenu","click","mouseover","mouseout","mousemove","mousedown","mouseup","mouseleave","mouseenter","dblclick"],{createEventArgs:e=>u(e)}),h(["error"],{createEventArgs:e=>{return{message:(t=e).message,filename:t.filename,lineno:t.lineno,colno:t.colno,type:t.type};var t}}),h(["loadstart","timeout","abort","load","loadend","progress"],{createEventArgs:e=>{return{lengthComputable:(t=e).lengthComputable,loaded:t.loaded,total:t.total,type:t.type};var t}}),h(["touchcancel","touchend","touchmove","touchenter","touchleave","touchstart"],{createEventArgs:e=>{return{detail:(t=e).detail,touches:d(t.touches),targetTouches:d(t.targetTouches),changedTouches:d(t.changedTouches),ctrlKey:t.ctrlKey,shiftKey:t.shiftKey,altKey:t.altKey,metaKey:t.metaKey,type:t.type};var t}}),h(["gotpointercapture","lostpointercapture","pointercancel","pointerdown","pointerenter","pointerleave","pointermove","pointerout","pointerover","pointerup"],{createEventArgs:e=>{return{...u(t=e),pointerId:t.pointerId,width:t.width,height:t.height,pressure:t.pressure,tiltX:t.tiltX,tiltY:t.tiltY,pointerType:t.pointerType,isPrimary:t.isPrimary};var t}}),h(["wheel","mousewheel"],{createEventArgs:e=>{return{...u(t=e),deltaX:t.deltaX,deltaY:t.deltaY,deltaZ:t.deltaZ,deltaMode:t.deltaMode};var t}}),h(["cancel","close","toggle"],{createEventArgs:()=>({})});const p=["date","datetime-local","month","time","week"],f=new Map;let g,m,v=0;const y={async add(e,t,n){if(!n)throw new Error("initialParameters must be an object, even if empty.");const o="__bl-dynamic-root:"+(++v).toString();f.set(o,e);const r=await b().invokeMethodAsync("AddRootComponent",t,o),s=new _(r,m[t]);return await s.setParameters(n),s}};class w{invoke(e){return this._callback(e)}setCallback(t){this._selfJSObjectReference||(this._selfJSObjectReference=e.createJSObjectReference(this)),this._callback=t}getJSObjectReference(){return this._selfJSObjectReference}dispose(){this._selfJSObjectReference&&e.disposeJSObjectReference(this._selfJSObjectReference)}}class _{constructor(e,t){this._jsEventCallbackWrappers=new Map,this._componentId=e;for(const e of t)"eventcallback"===e.type&&this._jsEventCallbackWrappers.set(e.name.toLowerCase(),new w)}setParameters(e){const t={},n=Object.entries(e||{}),o=n.length;for(const[e,o]of n){const n=this._jsEventCallbackWrappers.get(e.toLowerCase());n&&o?(n.setCallback(o),t[e]=n.getJSObjectReference()):t[e]=o}return b().invokeMethodAsync("SetRootComponentParameters",this._componentId,o,t)}async dispose(){if(null!==this._componentId){await b().invokeMethodAsync("RemoveRootComponent",this._componentId),this._componentId=null;for(const e of this._jsEventCallbackWrappers.values())e.dispose()}}}function b(){if(!g)throw new Error("Dynamic root components have not been enabled in this application.");return g}const S=new Map,E=[];let C;const I=new Promise((e=>{C=e}));function k(e,t,n){return D(e,t.eventHandlerId,(()=>T(e).invokeMethodAsync("DispatchEventAsync",t,n)))}function T(e){const t=S.get(e);if(!t)throw new Error(`No interop methods are registered for renderer ${e}`);return t}let D=(e,t,n)=>n();const x=M(["abort","blur","cancel","canplay","canplaythrough","change","close","cuechange","durationchange","emptied","ended","error","focus","load","loadeddata","loadedmetadata","loadend","loadstart","mouseenter","mouseleave","pointerenter","pointerleave","pause","play","playing","progress","ratechange","reset","scroll","seeked","seeking","stalled","submit","suspend","timeupdate","toggle","unload","volumechange","waiting","DOMNodeInsertedIntoDocument","DOMNodeRemovedFromDocument"]),R={submit:!0},P=M(["click","dblclick","mousedown","mousemove","mouseup"]);class A{constructor(e){this.browserRendererId=e,this.afterClickCallbacks=[];const t=++A.nextEventDelegatorId;this.eventsCollectionKey=`_blazorEvents_${t}`,this.eventInfoStore=new N(this.onGlobalEvent.bind(this))}setListener(e,t,n,o){const r=this.getEventHandlerInfosForElement(e,!0),s=r.getHandler(t);if(s)this.eventInfoStore.update(s.eventHandlerId,n);else{const s={element:e,eventName:t,eventHandlerId:n,renderingComponentId:o};this.eventInfoStore.add(s),r.setHandler(t,s)}}getHandler(e){return this.eventInfoStore.get(e)}removeListener(e){const t=this.eventInfoStore.remove(e);if(t){const e=t.element,n=this.getEventHandlerInfosForElement(e,!1);n&&n.removeHandler(t.eventName)}}notifyAfterClick(e){this.afterClickCallbacks.push(e),this.eventInfoStore.addGlobalListener("click")}setStopPropagation(e,t,n){this.getEventHandlerInfosForElement(e,!0).stopPropagation(t,n)}setPreventDefault(e,t,n){this.getEventHandlerInfosForElement(e,!0).preventDefault(t,n)}onGlobalEvent(e){if(!(e.target instanceof Element))return;this.dispatchGlobalEventToAllElements(e.type,e);const t=(n=e.type,i.get(n));var n;t&&t.forEach((t=>this.dispatchGlobalEventToAllElements(t,e))),"click"===e.type&&this.afterClickCallbacks.forEach((t=>t(e)))}dispatchGlobalEventToAllElements(e,t){const n=t.composedPath();let o=n.shift(),s=null,i=!1;const a=Object.prototype.hasOwnProperty.call(x,e);let l=!1;for(;o;){const u=o,p=this.getEventHandlerInfosForElement(u,!1);if(p){const n=p.getHandler(e);if(n&&(h=u,d=t.type,!((h instanceof HTMLButtonElement||h instanceof HTMLInputElement||h instanceof HTMLTextAreaElement||h instanceof HTMLSelectElement)&&Object.prototype.hasOwnProperty.call(P,d)&&h.disabled))){if(!i){const n=c(e);s=(null==n?void 0:n.createEventArgs)?n.createEventArgs(t):{},i=!0}Object.prototype.hasOwnProperty.call(R,t.type)&&t.preventDefault(),k(this.browserRendererId,{eventHandlerId:n.eventHandlerId,eventName:e,eventFieldInfo:r.fromEvent(n.renderingComponentId,t)},s)}p.stopPropagation(e)&&(l=!0),p.preventDefault(e)&&t.preventDefault()}o=a||l?void 0:n.shift()}var h,d}getEventHandlerInfosForElement(e,t){return Object.prototype.hasOwnProperty.call(e,this.eventsCollectionKey)?e[this.eventsCollectionKey]:t?e[this.eventsCollectionKey]=new U:null}}A.nextEventDelegatorId=0;class N{constructor(e){this.globalListener=e,this.infosByEventHandlerId={},this.countByEventName={},a.push(this.handleEventNameAliasAdded.bind(this))}add(e){if(this.infosByEventHandlerId[e.eventHandlerId])throw new Error(`Event ${e.eventHandlerId} is already tracked`);this.infosByEventHandlerId[e.eventHandlerId]=e,this.addGlobalListener(e.eventName)}get(e){return this.infosByEventHandlerId[e]}addGlobalListener(e){if(e=l(e),Object.prototype.hasOwnProperty.call(this.countByEventName,e))this.countByEventName[e]++;else{this.countByEventName[e]=1;const t=Object.prototype.hasOwnProperty.call(x,e);document.addEventListener(e,this.globalListener,t)}}update(e,t){if(Object.prototype.hasOwnProperty.call(this.infosByEventHandlerId,t))throw new Error(`Event ${t} is already tracked`);const n=this.infosByEventHandlerId[e];delete this.infosByEventHandlerId[e],n.eventHandlerId=t,this.infosByEventHandlerId[t]=n}remove(e){const t=this.infosByEventHandlerId[e];if(t){delete this.infosByEventHandlerId[e];const n=l(t.eventName);0==--this.countByEventName[n]&&(delete this.countByEventName[n],document.removeEventListener(n,this.globalListener))}return t}handleEventNameAliasAdded(e,t){if(Object.prototype.hasOwnProperty.call(this.countByEventName,e)){const n=this.countByEventName[e];delete this.countByEventName[e],document.removeEventListener(e,this.globalListener),this.addGlobalListener(t),this.countByEventName[t]+=n-1}}}class U{constructor(){this.handlers={},this.preventDefaultFlags=null,this.stopPropagationFlags=null}getHandler(e){return Object.prototype.hasOwnProperty.call(this.handlers,e)?this.handlers[e]:null}setHandler(e,t){this.handlers[e]=t}removeHandler(e){delete this.handlers[e]}preventDefault(e,t){return void 0!==t&&(this.preventDefaultFlags=this.preventDefaultFlags||{},this.preventDefaultFlags[e]=t),!!this.preventDefaultFlags&&this.preventDefaultFlags[e]}stopPropagation(e,t){return void 0!==t&&(this.stopPropagationFlags=this.stopPropagationFlags||{},this.stopPropagationFlags[e]=t),!!this.stopPropagationFlags&&this.stopPropagationFlags[e]}}function M(e){const t={};return e.forEach((e=>{t[e]=!0})),t}const B=Symbol(),L=Symbol(),$=Symbol();function O(e,t){if(B in e)return e;const n=[];if(e.childNodes.length>0){if(!t)throw new Error("New logical elements must start empty, or allowExistingContents must be true");e.childNodes.forEach((t=>{const o=O(t,!0);o[L]=e,n.push(o)}))}return e[B]=n,e}function F(e){const t=K(e);for(;t.length;)W(e,0)}function H(e,t){const n=document.createComment("!");return j(n,e,t),n}function j(e,t,n){const o=e;let r=e;if(B in e){const t=Q(o);if(t!==e){const n=new Range;n.setStartBefore(e),n.setEndAfter(t),r=n.extractContents()}}const s=z(o);if(s){const e=K(s),t=Array.prototype.indexOf.call(e,o);e.splice(t,1),delete o[L]}const i=K(t);if(n0;)W(n,0)}const o=n;o.parentNode.removeChild(o)}function z(e){return e[L]||null}function q(e,t){return K(e)[t]}function J(e){const t=Y(e);return"http://www.w3.org/2000/svg"===t.namespaceURI&&"foreignObject"!==t.tagName}function K(e){return e[B]}function V(e){const t=K(z(e));return t[Array.prototype.indexOf.call(t,e)+1]||null}function X(e,t){const n=K(e);t.forEach((e=>{e.moveRangeStart=n[e.fromSiblingIndex],e.moveRangeEnd=Q(e.moveRangeStart)})),t.forEach((t=>{const o=document.createComment("marker");t.moveToBeforeMarker=o;const r=n[t.toSiblingIndex+1];r?r.parentNode.insertBefore(o,r):G(o,e)})),t.forEach((e=>{const t=e.moveToBeforeMarker,n=t.parentNode,o=e.moveRangeStart,r=e.moveRangeEnd;let s=o;for(;s;){const e=s.nextSibling;if(n.insertBefore(s,t),s===r)break;s=e}n.removeChild(t)})),t.forEach((e=>{n[e.toSiblingIndex]=e.moveRangeStart}))}function Y(e){if(e instanceof Element||e instanceof DocumentFragment)return e;if(e instanceof Comment)return e.parentNode;throw new Error("Not a valid logical element")}function G(e,t){if(t instanceof Element||t instanceof DocumentFragment)t.appendChild(e);else{if(!(t instanceof Comment))throw new Error(`Cannot append node because the parent is not a valid logical element. Parent: ${t}`);{const n=V(t);n?n.parentNode.insertBefore(e,n):G(e,z(t))}}}function Q(e){if(e instanceof Element||e instanceof DocumentFragment)return e;const t=V(e);if(t)return t.previousSibling;{const t=z(e);return t instanceof Element||t instanceof DocumentFragment?t.lastChild:Q(t)}}function Z(e){return`_bl_${e}`}const ee="__internalId";e.attachReviver(((e,t)=>t&&"object"==typeof t&&Object.prototype.hasOwnProperty.call(t,ee)&&"string"==typeof t[ee]?function(e){const t=`[${Z(e)}]`;return document.querySelector(t)}(t[ee]):t));const te="_blazorDeferredValue";function ne(e){return"select-multiple"===e.type}function oe(e,t){e.value=t||""}function re(e,t){e instanceof HTMLSelectElement?ne(e)?function(e,t){t||(t=[]);for(let n=0;n{Ce()&&function(e,t){if(0!==e.button||function(e){return e.ctrlKey||e.shiftKey||e.altKey||e.metaKey}(e))return;if(e.defaultPrevented)return;const n=function(e){const t=!window._blazorDisableComposedPath&&e.composedPath&&e.composedPath();if(t){for(let e=0;edocument.baseURI,getLocationHref:()=>location.href,scrollToElement:Ue};function Ue(e){const t=document.getElementById(e);return!!t&&(t.scrollIntoView(),!0)}function Me(e,t,n=!1){const o=Se(e);!t.forceLoad&&we(o)?We()?Be(o,!1,t.replaceHistoryEntry,t.historyEntryState,n):be(o,t.replaceHistoryEntry):function(e,t){if(location.href===e){const t=e+"?";history.replaceState(null,"",t),location.replace(e)}else t?location.replace(e):location.href=e}(e,t.replaceHistoryEntry)}async function Be(e,t,n,o=void 0,r=!1){if(Oe(),function(e){const t=e.indexOf("#");return t>-1&&location.href.replace(location.hash,"")===e.substring(0,t)}(e))!function(e,t,n){Le(e,t,n);const o=e.indexOf("#");o!==e.length-1&&Ue(e.substring(o+1))}(e,n,o);else{if(!r&&ke&&!await Fe(e,o,t))return;ve=!0,Le(e,n,o),await He(t)}}function Le(e,t,n=void 0){t?history.replaceState({userState:n,_index:Te},"",e):(Te++,history.pushState({userState:n,_index:Te},"",e))}function $e(e){return new Promise((t=>{const n=Pe;Pe=()=>{Pe=n,t()},history.go(e)}))}function Oe(){Ae&&(Ae(!1),Ae=null)}function Fe(e,t,n){return new Promise((o=>{Oe(),Re?(De++,Ae=o,Re(De,e,t,n)):o(!1)}))}async function He(e){var t;xe&&await xe(location.href,null===(t=history.state)||void 0===t?void 0:t.userState,e)}async function je(e){var t,n;Pe&&We()&&await Pe(e),Te=null!==(n=null===(t=history.state)||void 0===t?void 0:t._index)&&void 0!==n?n:0}function We(){return Ce()||!_e()}const ze={focus:function(e,t){if(e instanceof HTMLElement)e.focus({preventScroll:t});else{if(!(e instanceof SVGElement))throw new Error("Unable to focus an invalid element.");if(!e.hasAttribute("tabindex"))throw new Error("Unable to focus an SVG element that does not have a tabindex.");e.focus({preventScroll:t})}},focusBySelector:function(e,t){const n=document.querySelector(e);n&&(n.hasAttribute("tabindex")||(n.tabIndex=-1),n.focus({preventScroll:!0}))}},qe={init:function(e,t,n,o=50){const r=Ke(t);(r||document.documentElement).style.overflowAnchor="none";const s=document.createRange();u(n.parentElement)&&(t.style.display="table-row",n.style.display="table-row");const i=new IntersectionObserver((function(o){o.forEach((o=>{var r;if(!o.isIntersecting)return;s.setStartAfter(t),s.setEndBefore(n);const i=s.getBoundingClientRect().height,a=null===(r=o.rootBounds)||void 0===r?void 0:r.height;o.target===t?e.invokeMethodAsync("OnSpacerBeforeVisible",o.intersectionRect.top-o.boundingClientRect.top,i,a):o.target===n&&n.offsetHeight>0&&e.invokeMethodAsync("OnSpacerAfterVisible",o.boundingClientRect.bottom-o.intersectionRect.bottom,i,a)}))}),{root:r,rootMargin:`${o}px`});i.observe(t),i.observe(n);const a=d(t),c=d(n),{observersByDotNetObjectId:l,id:h}=Ve(e);function d(e){const t={attributes:!0},n=new MutationObserver(((n,o)=>{u(e.parentElement)&&(o.disconnect(),e.style.display="table-row",o.observe(e,t)),i.unobserve(e),i.observe(e)}));return n.observe(e,t),n}function u(e){return null!==e&&(e instanceof HTMLTableElement&&""===e.style.display||"table"===e.style.display||e instanceof HTMLTableSectionElement&&""===e.style.display||"table-row-group"===e.style.display)}l[h]={intersectionObserver:i,mutationObserverBefore:a,mutationObserverAfter:c}},dispose:function(e){const{observersByDotNetObjectId:t,id:n}=Ve(e),o=t[n];o&&(o.intersectionObserver.disconnect(),o.mutationObserverBefore.disconnect(),o.mutationObserverAfter.disconnect(),e.dispose(),delete t[n])}},Je=Symbol();function Ke(e){return e&&e!==document.body&&e!==document.documentElement?"visible"!==getComputedStyle(e).overflowY?e:Ke(e.parentElement):null}function Ve(e){var t;const n=e._callDispatcher,o=e._id;return null!==(t=n[Je])&&void 0!==t||(n[Je]={}),{observersByDotNetObjectId:n[Je],id:o}}const Xe={getAndRemoveExistingTitle:function(){var e;const t=document.head?document.head.getElementsByTagName("title"):[];if(0===t.length)return null;let n=null;for(let o=t.length-1;o>=0;o--){const r=t[o],s=r.previousSibling;s instanceof Comment&&null!==z(s)||(null===n&&(n=r.textContent),null===(e=r.parentNode)||void 0===e||e.removeChild(r))}return n}},Ye={init:function(e,t){t._blazorInputFileNextFileId=0,t.addEventListener("click",(function(){t.value=""})),t.addEventListener("change",(function(){t._blazorFilesById={};const n=Array.prototype.map.call(t.files,(function(e){const n={id:++t._blazorInputFileNextFileId,lastModified:new Date(e.lastModified).toISOString(),name:e.name,size:e.size,contentType:e.type,readPromise:void 0,arrayBuffer:void 0,blob:e};return t._blazorFilesById[n.id]=n,n}));e.invokeMethodAsync("NotifyChange",n)}))},toImageFile:async function(e,t,n,o,r){const s=Ge(e,t),i=await new Promise((function(e){const t=new Image;t.onload=function(){URL.revokeObjectURL(t.src),e(t)},t.onerror=function(){t.onerror=null,URL.revokeObjectURL(t.src)},t.src=URL.createObjectURL(s.blob)})),a=await new Promise((function(e){var t;const s=Math.min(1,o/i.width),a=Math.min(1,r/i.height),c=Math.min(s,a),l=document.createElement("canvas");l.width=Math.round(i.width*c),l.height=Math.round(i.height*c),null===(t=l.getContext("2d"))||void 0===t||t.drawImage(i,0,0,l.width,l.height),l.toBlob(e,n)})),c={id:++e._blazorInputFileNextFileId,lastModified:s.lastModified,name:s.name,size:(null==a?void 0:a.size)||0,contentType:n,blob:a||s.blob};return e._blazorFilesById[c.id]=c,c},readFileData:async function(e,t){return Ge(e,t).blob}};function Ge(e,t){const n=e._blazorFilesById[t];if(!n)throw new Error(`There is no file with ID ${t}. The file list may have changed. See https://aka.ms/aspnet/blazor-input-file-multiple-selections.`);return n}const Qe=new Set,Ze={enableNavigationPrompt:function(e){0===Qe.size&&window.addEventListener("beforeunload",et),Qe.add(e)},disableNavigationPrompt:function(e){Qe.delete(e),0===Qe.size&&window.removeEventListener("beforeunload",et)}};function et(e){e.preventDefault(),e.returnValue=!0}async function tt(e,t,n){return e instanceof Blob?await async function(e,t,n){const o=e.slice(t,t+n),r=await o.arrayBuffer();return new Uint8Array(r)}(e,t,n):function(e,t,n){return new Uint8Array(e.buffer,e.byteOffset+t,n)}(e,t,n)}new Map;const nt={navigateTo:function(e,t,n=!1){Me(e,t instanceof Object?t:{forceLoad:t,replaceHistoryEntry:n})},registerCustomEventType:function(e,t){if(!t)throw new Error("The options parameter is required.");if(s.has(e))throw new Error(`The event '${e}' is already registered.`);if(t.browserEventName){const n=i.get(t.browserEventName);n?n.push(e):i.set(t.browserEventName,[e]),a.forEach((n=>n(e,t.browserEventName)))}s.set(e,t)},rootComponents:y,runtime:{},_internal:{navigationManager:Ne,domWrapper:ze,Virtualize:qe,PageTitle:Xe,InputFile:Ye,NavigationLock:Ze,getJSDataStreamChunk:tt,attachWebRendererInterop:function(t,n,o,r){if(S.has(t))throw new Error(`Interop methods are already registered for renderer ${t}`);S.set(t,n),Object.keys(o).length>0&&function(t,n,o){if(g)throw new Error("Dynamic root components have already been enabled.");g=t,m=n;for(const[t,r]of Object.entries(o)){const o=e.findJSFunction(t,0);for(const e of r)o(e,n[e])}}(T(t),o,r),C(),function(e){for(const t of E)t(e)}(t)}}};var ot;window.Blazor=nt,function(e){e[e.Trace=0]="Trace",e[e.Debug=1]="Debug",e[e.Information=2]="Information",e[e.Warning=3]="Warning",e[e.Error=4]="Error",e[e.Critical=5]="Critical",e[e.None=6]="None"}(ot||(ot={}));class rt{log(e,t){}}rt.instance=new rt;class st{constructor(e){this.minLevel=e}log(e,t){if(e>=this.minLevel){const n=`[${(new Date).toISOString()}] ${ot[e]}: ${t}`;switch(e){case ot.Critical:case ot.Error:console.error(n);break;case ot.Warning:console.warn(n);break;case ot.Information:console.info(n);break;default:console.log(n)}}}}const it=/^\s*Blazor-Component-State:(?[a-zA-Z0-9+/=]+)$/;function at(e){var t;if(e.nodeType===Node.COMMENT_NODE){const n=e.textContent||"",o=it.exec(n),r=o&&o.groups&&o.groups.state;return r&&(null===(t=e.parentNode)||void 0===t||t.removeChild(e)),r}if(!e.hasChildNodes())return;const n=e.childNodes;for(let e=0;e.*)$/);function ht(e,t){const n=e.currentElement;var o,r,s;if(n&&n.nodeType===Node.COMMENT_NODE&&n.textContent){const i=lt.exec(n.textContent),a=i&&i.groups&&i.groups.descriptor;if(!a)return;!function(e){if(e.parentNode instanceof Document)throw new Error("Root components cannot be marked as interactive. The element must be rendered statically so that scripts are not evaluated multiple times.")}(n);try{const i=function(e){const t=JSON.parse(e),{type:n}=t;if("server"!==n&&"webassembly"!==n&&"auto"!==n)throw new Error(`Invalid component type '${n}'.`);return t}(a),c=function(e,t,n){const{prerenderId:o}=e;if(o){for(;n.next()&&n.currentElement;){const e=n.currentElement;if(e.nodeType!==Node.COMMENT_NODE)continue;if(!e.textContent)continue;const t=lt.exec(e.textContent),r=t&&t[1];if(r)return ft(r,o),e}throw new Error(`Could not find an end component comment for '${t}'.`)}}(i,n,e);if(t!==i.type)return;switch(i.type){case"webassembly":return r=n,s=c,pt(o=i),{...o,uniqueId:dt++,start:r,end:s};case"server":return function(e,t,n){return ut(e),{...e,uniqueId:dt++,start:t,end:n}}(i,n,c);case"auto":return function(e,t,n){return ut(e),pt(e),{...e,uniqueId:dt++,start:t,end:n}}(i,n,c)}}catch(e){throw new Error(`Found malformed component comment at ${n.textContent}`)}}}let dt=0;function ut(e){const{descriptor:t,sequence:n}=e;if(!t)throw new Error("descriptor must be defined when using a descriptor.");if(void 0===n)throw new Error("sequence must be defined when using a descriptor.");if(!Number.isInteger(n))throw new Error(`Error parsing the sequence '${n}' for component '${JSON.stringify(e)}'`)}function pt(e){const{assembly:t,typeName:n}=e;if(!t)throw new Error("assembly must be defined when using a descriptor.");if(!n)throw new Error("typeName must be defined when using a descriptor.");e.parameterDefinitions=e.parameterDefinitions&&atob(e.parameterDefinitions),e.parameterValues=e.parameterValues&&atob(e.parameterValues)}function ft(e,t){const n=JSON.parse(e);if(1!==Object.keys(n).length)throw new Error(`Invalid end of component comment: '${e}'`);const o=n.prerenderId;if(!o)throw new Error(`End of component comment must have a value for the prerendered property: '${e}'`);if(o!==t)throw new Error(`End of component comment prerendered property must match the start comment prerender id: '${t}', '${o}'`)}class gt{constructor(e){this.childNodes=e,this.currentIndex=-1,this.length=e.length}next(){return this.currentIndex++,this.currentIndex{n+=`0x${e<16?"0":""}${e.toString(16)} `})),n.substr(0,n.length-1)}(e)}'`)):"string"==typeof e&&(n=`String data of length ${e.length}`,t&&(n+=`. Content: '${e}'`)),n}function Et(e){return e&&"undefined"!=typeof ArrayBuffer&&(e instanceof ArrayBuffer||e.constructor&&"ArrayBuffer"===e.constructor.name)}async function Ct(e,t,n,o,r,s){const i={},[a,c]=Tt();i[a]=c,e.log(vt.Trace,`(${t} transport) sending data. ${St(r,s.logMessageContent)}.`);const l=Et(r)?"arraybuffer":"text",h=await n.post(o,{content:r,headers:{...i,...s.headers},responseType:l,timeout:s.timeout,withCredentials:s.withCredentials});e.log(vt.Trace,`(${t} transport) request complete. Response status: ${h.statusCode}.`)}class It{constructor(e,t){this._subject=e,this._observer=t}dispose(){const e=this._subject.observers.indexOf(this._observer);e>-1&&this._subject.observers.splice(e,1),0===this._subject.observers.length&&this._subject.cancelCallback&&this._subject.cancelCallback().catch((e=>{}))}}class kt{constructor(e){this._minLevel=e,this.out=console}log(e,t){if(e>=this._minLevel){const n=`[${(new Date).toISOString()}] ${vt[e]}: ${t}`;switch(e){case vt.Critical:case vt.Error:this.out.error(n);break;case vt.Warning:this.out.warn(n);break;case vt.Information:this.out.info(n);break;default:this.out.log(n)}}}}function Tt(){let e="X-SignalR-User-Agent";return bt.isNode&&(e="User-Agent"),[e,Dt(wt,xt(),bt.isNode?"NodeJS":"Browser",Rt())]}function Dt(e,t,n,o){let r="Microsoft SignalR/";const s=e.split(".");return r+=`${s[0]}.${s[1]}`,r+=` (${e}; `,r+=t&&""!==t?`${t}; `:"Unknown OS; ",r+=`${n}`,r+=o?`; ${o}`:"; Unknown Runtime Version",r+=")",r}function xt(){if(!bt.isNode)return"";switch(process.platform){case"win32":return"Windows NT";case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}}function Rt(){if(bt.isNode)return process.versions.node}function Pt(e){return e.stack?e.stack:e.message?e.message:`${e}`}class At{writeHandshakeRequest(e){return mt.write(JSON.stringify(e))}parseHandshakeResponse(e){let t,n;if(Et(e)){const o=new Uint8Array(e),r=o.indexOf(mt.RecordSeparatorCode);if(-1===r)throw new Error("Message is incomplete.");const s=r+1;t=String.fromCharCode.apply(null,Array.prototype.slice.call(o.slice(0,s))),n=o.byteLength>s?o.slice(s).buffer:null}else{const o=e,r=o.indexOf(mt.RecordSeparator);if(-1===r)throw new Error("Message is incomplete.");const s=r+1;t=o.substring(0,s),n=o.length>s?o.substring(s):null}const o=mt.parse(t),r=JSON.parse(o[0]);if(r.type)throw new Error("Expected a handshake response from the server.");return[n,r]}}class Nt extends Error{constructor(e,t){const n=new.target.prototype;super(`${e}: Status code '${t}'`),this.statusCode=t,this.__proto__=n}}class Ut extends Error{constructor(e="A timeout occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class Mt extends Error{constructor(e="An abort occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class Bt extends Error{constructor(e,t){const n=new.target.prototype;super(e),this.transport=t,this.errorType="UnsupportedTransportError",this.__proto__=n}}class Lt extends Error{constructor(e,t){const n=new.target.prototype;super(e),this.transport=t,this.errorType="DisabledTransportError",this.__proto__=n}}class $t extends Error{constructor(e,t){const n=new.target.prototype;super(e),this.transport=t,this.errorType="FailedToStartTransportError",this.__proto__=n}}class Ot extends Error{constructor(e){const t=new.target.prototype;super(e),this.errorType="FailedToNegotiateWithServerError",this.__proto__=t}}class Ft extends Error{constructor(e,t){const n=new.target.prototype;super(e),this.innerErrors=t,this.__proto__=n}}var Ht,jt;!function(e){e[e.Invocation=1]="Invocation",e[e.StreamItem=2]="StreamItem",e[e.Completion=3]="Completion",e[e.StreamInvocation=4]="StreamInvocation",e[e.CancelInvocation=5]="CancelInvocation",e[e.Ping=6]="Ping",e[e.Close=7]="Close",e[e.Ack=8]="Ack",e[e.Sequence=9]="Sequence"}(Ht||(Ht={}));class Wt{constructor(){this.observers=[]}next(e){for(const t of this.observers)t.next(e)}error(e){for(const t of this.observers)t.error&&t.error(e)}complete(){for(const e of this.observers)e.complete&&e.complete()}subscribe(e){return this.observers.push(e),new It(this,e)}}class zt{constructor(e,t,n){this._bufferSize=1e5,this._messages=[],this._totalMessageCount=0,this._waitForSequenceMessage=!1,this._nextReceivingSequenceId=1,this._latestReceivedSequenceId=0,this._bufferedByteCount=0,this._reconnectInProgress=!1,this._protocol=e,this._connection=t,this._bufferSize=n}async _send(e){const t=this._protocol.writeMessage(e);let n=Promise.resolve();if(this._isInvocationMessage(e)){this._totalMessageCount++;let e=()=>{},o=()=>{};Et(t)?this._bufferedByteCount+=t.byteLength:this._bufferedByteCount+=t.length,this._bufferedByteCount>=this._bufferSize&&(n=new Promise(((t,n)=>{e=t,o=n}))),this._messages.push(new qt(t,this._totalMessageCount,e,o))}try{this._reconnectInProgress||await this._connection.send(t)}catch{this._disconnected()}await n}_ack(e){let t=-1;for(let n=0;nthis._nextReceivingSequenceId?this._connection.stop(new Error("Sequence ID greater than amount of messages we've received.")):this._nextReceivingSequenceId=e.sequenceId}_disconnected(){this._reconnectInProgress=!0,this._waitForSequenceMessage=!0}async _resend(){const e=0!==this._messages.length?this._messages[0]._id:this._totalMessageCount+1;await this._connection.send(this._protocol.writeMessage({type:Ht.Sequence,sequenceId:e}));const t=this._messages;for(const e of t)await this._connection.send(e._message);this._reconnectInProgress=!1}_dispose(e){null!=e||(e=new Error("Unable to reconnect to server."));for(const t of this._messages)t._rejector(e)}_isInvocationMessage(e){switch(e.type){case Ht.Invocation:case Ht.StreamItem:case Ht.Completion:case Ht.StreamInvocation:case Ht.CancelInvocation:return!0;case Ht.Close:case Ht.Sequence:case Ht.Ping:case Ht.Ack:return!1}}_ackTimer(){void 0===this._ackTimerHandle&&(this._ackTimerHandle=setTimeout((async()=>{try{this._reconnectInProgress||await this._connection.send(this._protocol.writeMessage({type:Ht.Ack,sequenceId:this._latestReceivedSequenceId}))}catch{}clearTimeout(this._ackTimerHandle),this._ackTimerHandle=void 0}),1e3))}}class qt{constructor(e,t,n,o){this._message=e,this._id=t,this._resolver=n,this._rejector=o}}!function(e){e.Disconnected="Disconnected",e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Reconnecting="Reconnecting"}(jt||(jt={}));class Jt{static create(e,t,n,o,r,s,i){return new Jt(e,t,n,o,r,s,i)}constructor(e,t,n,o,r,s,i){this._nextKeepAlive=0,this._freezeEventListener=()=>{this._logger.log(vt.Warning,"The page is being frozen, this will likely lead to the connection being closed and messages being lost. For more information see the docs at https://learn.microsoft.com/aspnet/core/signalr/javascript-client#bsleep")},_t.isRequired(e,"connection"),_t.isRequired(t,"logger"),_t.isRequired(n,"protocol"),this.serverTimeoutInMilliseconds=null!=r?r:3e4,this.keepAliveIntervalInMilliseconds=null!=s?s:15e3,this._statefulReconnectBufferSize=null!=i?i:1e5,this._logger=t,this._protocol=n,this.connection=e,this._reconnectPolicy=o,this._handshakeProtocol=new At,this.connection.onreceive=e=>this._processIncomingData(e),this.connection.onclose=e=>this._connectionClosed(e),this._callbacks={},this._methods={},this._closedCallbacks=[],this._reconnectingCallbacks=[],this._reconnectedCallbacks=[],this._invocationId=0,this._receivedHandshakeResponse=!1,this._connectionState=jt.Disconnected,this._connectionStarted=!1,this._cachedPingMessage=this._protocol.writeMessage({type:Ht.Ping})}get state(){return this._connectionState}get connectionId(){return this.connection&&this.connection.connectionId||null}get baseUrl(){return this.connection.baseUrl||""}set baseUrl(e){if(this._connectionState!==jt.Disconnected&&this._connectionState!==jt.Reconnecting)throw new Error("The HubConnection must be in the Disconnected or Reconnecting state to change the url.");if(!e)throw new Error("The HubConnection url must be a valid url.");this.connection.baseUrl=e}start(){return this._startPromise=this._startWithStateTransitions(),this._startPromise}async _startWithStateTransitions(){if(this._connectionState!==jt.Disconnected)return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."));this._connectionState=jt.Connecting,this._logger.log(vt.Debug,"Starting HubConnection.");try{await this._startInternal(),bt.isBrowser&&window.document.addEventListener("freeze",this._freezeEventListener),this._connectionState=jt.Connected,this._connectionStarted=!0,this._logger.log(vt.Debug,"HubConnection connected successfully.")}catch(e){return this._connectionState=jt.Disconnected,this._logger.log(vt.Debug,`HubConnection failed to start successfully because of error '${e}'.`),Promise.reject(e)}}async _startInternal(){this._stopDuringStartError=void 0,this._receivedHandshakeResponse=!1;const e=new Promise(((e,t)=>{this._handshakeResolver=e,this._handshakeRejecter=t}));await this.connection.start(this._protocol.transferFormat);try{let t=this._protocol.version;this.connection.features.reconnect||(t=1);const n={protocol:this._protocol.name,version:t};if(this._logger.log(vt.Debug,"Sending handshake request."),await this._sendMessage(this._handshakeProtocol.writeHandshakeRequest(n)),this._logger.log(vt.Information,`Using HubProtocol '${this._protocol.name}'.`),this._cleanupTimeout(),this._resetTimeoutPeriod(),this._resetKeepAliveInterval(),await e,this._stopDuringStartError)throw this._stopDuringStartError;!!this.connection.features.reconnect&&(this._messageBuffer=new zt(this._protocol,this.connection,this._statefulReconnectBufferSize),this.connection.features.disconnected=this._messageBuffer._disconnected.bind(this._messageBuffer),this.connection.features.resend=()=>{if(this._messageBuffer)return this._messageBuffer._resend()}),this.connection.features.inherentKeepAlive||await this._sendMessage(this._cachedPingMessage)}catch(e){throw this._logger.log(vt.Debug,`Hub handshake failed with error '${e}' during start(). Stopping HubConnection.`),this._cleanupTimeout(),this._cleanupPingTimer(),await this.connection.stop(e),e}}async stop(){const e=this._startPromise;this.connection.features.reconnect=!1,this._stopPromise=this._stopInternal(),await this._stopPromise;try{await e}catch(e){}}_stopInternal(e){if(this._connectionState===jt.Disconnected)return this._logger.log(vt.Debug,`Call to HubConnection.stop(${e}) ignored because it is already in the disconnected state.`),Promise.resolve();if(this._connectionState===jt.Disconnecting)return this._logger.log(vt.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnecting state.`),this._stopPromise;const t=this._connectionState;return this._connectionState=jt.Disconnecting,this._logger.log(vt.Debug,"Stopping HubConnection."),this._reconnectDelayHandle?(this._logger.log(vt.Debug,"Connection stopped during reconnect delay. Done reconnecting."),clearTimeout(this._reconnectDelayHandle),this._reconnectDelayHandle=void 0,this._completeClose(),Promise.resolve()):(t===jt.Connected&&this._sendCloseMessage(),this._cleanupTimeout(),this._cleanupPingTimer(),this._stopDuringStartError=e||new Mt("The connection was stopped before the hub handshake could complete."),this.connection.stop(e))}async _sendCloseMessage(){try{await this._sendWithProtocol(this._createCloseMessage())}catch{}}stream(e,...t){const[n,o]=this._replaceStreamingParams(t),r=this._createStreamInvocation(e,t,o);let s;const i=new Wt;return i.cancelCallback=()=>{const e=this._createCancelInvocation(r.invocationId);return delete this._callbacks[r.invocationId],s.then((()=>this._sendWithProtocol(e)))},this._callbacks[r.invocationId]=(e,t)=>{t?i.error(t):e&&(e.type===Ht.Completion?e.error?i.error(new Error(e.error)):i.complete():i.next(e.item))},s=this._sendWithProtocol(r).catch((e=>{i.error(e),delete this._callbacks[r.invocationId]})),this._launchStreams(n,s),i}_sendMessage(e){return this._resetKeepAliveInterval(),this.connection.send(e)}_sendWithProtocol(e){return this._messageBuffer?this._messageBuffer._send(e):this._sendMessage(this._protocol.writeMessage(e))}send(e,...t){const[n,o]=this._replaceStreamingParams(t),r=this._sendWithProtocol(this._createInvocation(e,t,!0,o));return this._launchStreams(n,r),r}invoke(e,...t){const[n,o]=this._replaceStreamingParams(t),r=this._createInvocation(e,t,!1,o);return new Promise(((e,t)=>{this._callbacks[r.invocationId]=(n,o)=>{o?t(o):n&&(n.type===Ht.Completion?n.error?t(new Error(n.error)):e(n.result):t(new Error(`Unexpected message type: ${n.type}`)))};const o=this._sendWithProtocol(r).catch((e=>{t(e),delete this._callbacks[r.invocationId]}));this._launchStreams(n,o)}))}on(e,t){e&&t&&(e=e.toLowerCase(),this._methods[e]||(this._methods[e]=[]),-1===this._methods[e].indexOf(t)&&this._methods[e].push(t))}off(e,t){if(!e)return;e=e.toLowerCase();const n=this._methods[e];if(n)if(t){const o=n.indexOf(t);-1!==o&&(n.splice(o,1),0===n.length&&delete this._methods[e])}else delete this._methods[e]}onclose(e){e&&this._closedCallbacks.push(e)}onreconnecting(e){e&&this._reconnectingCallbacks.push(e)}onreconnected(e){e&&this._reconnectedCallbacks.push(e)}_processIncomingData(e){if(this._cleanupTimeout(),this._receivedHandshakeResponse||(e=this._processHandshakeResponse(e),this._receivedHandshakeResponse=!0),e){const t=this._protocol.parseMessages(e,this._logger);for(const e of t)if(!this._messageBuffer||this._messageBuffer._shouldProcessMessage(e))switch(e.type){case Ht.Invocation:this._invokeClientMethod(e);break;case Ht.StreamItem:case Ht.Completion:{const t=this._callbacks[e.invocationId];if(t){e.type===Ht.Completion&&delete this._callbacks[e.invocationId];try{t(e)}catch(e){this._logger.log(vt.Error,`Stream callback threw error: ${Pt(e)}`)}}break}case Ht.Ping:break;case Ht.Close:{this._logger.log(vt.Information,"Close message received from server.");const t=e.error?new Error("Server returned an error on close: "+e.error):void 0;!0===e.allowReconnect?this.connection.stop(t):this._stopPromise=this._stopInternal(t);break}case Ht.Ack:this._messageBuffer&&this._messageBuffer._ack(e);break;case Ht.Sequence:this._messageBuffer&&this._messageBuffer._resetSequence(e);break;default:this._logger.log(vt.Warning,`Invalid message type: ${e.type}.`)}}this._resetTimeoutPeriod()}_processHandshakeResponse(e){let t,n;try{[n,t]=this._handshakeProtocol.parseHandshakeResponse(e)}catch(e){const t="Error parsing handshake response: "+e;this._logger.log(vt.Error,t);const n=new Error(t);throw this._handshakeRejecter(n),n}if(t.error){const e="Server returned handshake error: "+t.error;this._logger.log(vt.Error,e);const n=new Error(e);throw this._handshakeRejecter(n),n}return this._logger.log(vt.Debug,"Server handshake complete."),this._handshakeResolver(),n}_resetKeepAliveInterval(){this.connection.features.inherentKeepAlive||(this._nextKeepAlive=(new Date).getTime()+this.keepAliveIntervalInMilliseconds,this._cleanupPingTimer())}_resetTimeoutPeriod(){if(!(this.connection.features&&this.connection.features.inherentKeepAlive||(this._timeoutHandle=setTimeout((()=>this.serverTimeout()),this.serverTimeoutInMilliseconds),void 0!==this._pingServerHandle))){let e=this._nextKeepAlive-(new Date).getTime();e<0&&(e=0),this._pingServerHandle=setTimeout((async()=>{if(this._connectionState===jt.Connected)try{await this._sendMessage(this._cachedPingMessage)}catch{this._cleanupPingTimer()}}),e)}}serverTimeout(){this.connection.stop(new Error("Server timeout elapsed without receiving a message from the server."))}async _invokeClientMethod(e){const t=e.target.toLowerCase(),n=this._methods[t];if(!n)return this._logger.log(vt.Warning,`No client method with the name '${t}' found.`),void(e.invocationId&&(this._logger.log(vt.Warning,`No result given for '${t}' method and invocation ID '${e.invocationId}'.`),await this._sendWithProtocol(this._createCompletionMessage(e.invocationId,"Client didn't provide a result.",null))));const o=n.slice(),r=!!e.invocationId;let s,i,a;for(const n of o)try{const o=s;s=await n.apply(this,e.arguments),r&&s&&o&&(this._logger.log(vt.Error,`Multiple results provided for '${t}'. Sending error to server.`),a=this._createCompletionMessage(e.invocationId,"Client provided multiple results.",null)),i=void 0}catch(e){i=e,this._logger.log(vt.Error,`A callback for the method '${t}' threw error '${e}'.`)}a?await this._sendWithProtocol(a):r?(i?a=this._createCompletionMessage(e.invocationId,`${i}`,null):void 0!==s?a=this._createCompletionMessage(e.invocationId,null,s):(this._logger.log(vt.Warning,`No result given for '${t}' method and invocation ID '${e.invocationId}'.`),a=this._createCompletionMessage(e.invocationId,"Client didn't provide a result.",null)),await this._sendWithProtocol(a)):s&&this._logger.log(vt.Error,`Result given for '${t}' method but server is not expecting a result.`)}_connectionClosed(e){this._logger.log(vt.Debug,`HubConnection.connectionClosed(${e}) called while in state ${this._connectionState}.`),this._stopDuringStartError=this._stopDuringStartError||e||new Mt("The underlying connection was closed before the hub handshake could complete."),this._handshakeResolver&&this._handshakeResolver(),this._cancelCallbacksWithError(e||new Error("Invocation canceled due to the underlying connection being closed.")),this._cleanupTimeout(),this._cleanupPingTimer(),this._connectionState===jt.Disconnecting?this._completeClose(e):this._connectionState===jt.Connected&&this._reconnectPolicy?this._reconnect(e):this._connectionState===jt.Connected&&this._completeClose(e)}_completeClose(e){if(this._connectionStarted){this._connectionState=jt.Disconnected,this._connectionStarted=!1,this._messageBuffer&&(this._messageBuffer._dispose(null!=e?e:new Error("Connection closed.")),this._messageBuffer=void 0),bt.isBrowser&&window.document.removeEventListener("freeze",this._freezeEventListener);try{this._closedCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(vt.Error,`An onclose callback called with error '${e}' threw error '${t}'.`)}}}async _reconnect(e){const t=Date.now();let n=0,o=void 0!==e?e:new Error("Attempting to reconnect due to a unknown error."),r=this._getNextRetryDelay(n++,0,o);if(null===r)return this._logger.log(vt.Debug,"Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt."),void this._completeClose(e);if(this._connectionState=jt.Reconnecting,e?this._logger.log(vt.Information,`Connection reconnecting because of error '${e}'.`):this._logger.log(vt.Information,"Connection reconnecting."),0!==this._reconnectingCallbacks.length){try{this._reconnectingCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(vt.Error,`An onreconnecting callback called with error '${e}' threw error '${t}'.`)}if(this._connectionState!==jt.Reconnecting)return void this._logger.log(vt.Debug,"Connection left the reconnecting state in onreconnecting callback. Done reconnecting.")}for(;null!==r;){if(this._logger.log(vt.Information,`Reconnect attempt number ${n} will start in ${r} ms.`),await new Promise((e=>{this._reconnectDelayHandle=setTimeout(e,r)})),this._reconnectDelayHandle=void 0,this._connectionState!==jt.Reconnecting)return void this._logger.log(vt.Debug,"Connection left the reconnecting state during reconnect delay. Done reconnecting.");try{if(await this._startInternal(),this._connectionState=jt.Connected,this._logger.log(vt.Information,"HubConnection reconnected successfully."),0!==this._reconnectedCallbacks.length)try{this._reconnectedCallbacks.forEach((e=>e.apply(this,[this.connection.connectionId])))}catch(e){this._logger.log(vt.Error,`An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${e}'.`)}return}catch(e){if(this._logger.log(vt.Information,`Reconnect attempt failed because of error '${e}'.`),this._connectionState!==jt.Reconnecting)return this._logger.log(vt.Debug,`Connection moved to the '${this._connectionState}' from the reconnecting state during reconnect attempt. Done reconnecting.`),void(this._connectionState===jt.Disconnecting&&this._completeClose());o=e instanceof Error?e:new Error(e.toString()),r=this._getNextRetryDelay(n++,Date.now()-t,o)}}this._logger.log(vt.Information,`Reconnect retries have been exhausted after ${Date.now()-t} ms and ${n} failed attempts. Connection disconnecting.`),this._completeClose()}_getNextRetryDelay(e,t,n){try{return this._reconnectPolicy.nextRetryDelayInMilliseconds({elapsedMilliseconds:t,previousRetryCount:e,retryReason:n})}catch(n){return this._logger.log(vt.Error,`IRetryPolicy.nextRetryDelayInMilliseconds(${e}, ${t}) threw error '${n}'.`),null}}_cancelCallbacksWithError(e){const t=this._callbacks;this._callbacks={},Object.keys(t).forEach((n=>{const o=t[n];try{o(null,e)}catch(t){this._logger.log(vt.Error,`Stream 'error' callback called with '${e}' threw error: ${Pt(t)}`)}}))}_cleanupPingTimer(){this._pingServerHandle&&(clearTimeout(this._pingServerHandle),this._pingServerHandle=void 0)}_cleanupTimeout(){this._timeoutHandle&&clearTimeout(this._timeoutHandle)}_createInvocation(e,t,n,o){if(n)return 0!==o.length?{arguments:t,streamIds:o,target:e,type:Ht.Invocation}:{arguments:t,target:e,type:Ht.Invocation};{const n=this._invocationId;return this._invocationId++,0!==o.length?{arguments:t,invocationId:n.toString(),streamIds:o,target:e,type:Ht.Invocation}:{arguments:t,invocationId:n.toString(),target:e,type:Ht.Invocation}}}_launchStreams(e,t){if(0!==e.length){t||(t=Promise.resolve());for(const n in e)e[n].subscribe({complete:()=>{t=t.then((()=>this._sendWithProtocol(this._createCompletionMessage(n))))},error:e=>{let o;o=e instanceof Error?e.message:e&&e.toString?e.toString():"Unknown error",t=t.then((()=>this._sendWithProtocol(this._createCompletionMessage(n,o))))},next:e=>{t=t.then((()=>this._sendWithProtocol(this._createStreamItemMessage(n,e))))}})}}_replaceStreamingParams(e){const t=[],n=[];for(let o=0;o0)&&(t=!1,this._accessToken=await this._accessTokenFactory()),this._setAuthorizationHeader(e);const n=await this._innerClient.send(e);return t&&401===n.statusCode&&this._accessTokenFactory?(this._accessToken=await this._accessTokenFactory(),this._setAuthorizationHeader(e),await this._innerClient.send(e)):n}_setAuthorizationHeader(e){e.headers||(e.headers={}),this._accessToken?e.headers[Xt.Authorization]=`Bearer ${this._accessToken}`:this._accessTokenFactory&&e.headers[Xt.Authorization]&&delete e.headers[Xt.Authorization]}getCookieString(e){return this._innerClient.getCookieString(e)}}class Zt extends Gt{constructor(e){super(),this._logger=e;const t={_fetchType:void 0,_jar:void 0};var o;o=t,"undefined"==typeof fetch&&(o._jar=new(n(628).CookieJar),"undefined"==typeof fetch?o._fetchType=n(200):o._fetchType=fetch,o._fetchType=n(203)(o._fetchType,o._jar),1)?(this._fetchType=t._fetchType,this._jar=t._jar):this._fetchType=fetch.bind(function(){if("undefined"!=typeof globalThis)return globalThis;if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if(void 0!==n.g)return n.g;throw new Error("could not find global")}()),this._abortControllerType=AbortController;const r={_abortControllerType:this._abortControllerType};(function(e){return"undefined"==typeof AbortController&&(e._abortControllerType=n(778),!0)})(r)&&(this._abortControllerType=r._abortControllerType)}async send(e){if(e.abortSignal&&e.abortSignal.aborted)throw new Mt;if(!e.method)throw new Error("No method defined.");if(!e.url)throw new Error("No url defined.");const t=new this._abortControllerType;let n;e.abortSignal&&(e.abortSignal.onabort=()=>{t.abort(),n=new Mt});let o,r=null;if(e.timeout){const o=e.timeout;r=setTimeout((()=>{t.abort(),this._logger.log(vt.Warning,"Timeout from HTTP request."),n=new Ut}),o)}""===e.content&&(e.content=void 0),e.content&&(e.headers=e.headers||{},Et(e.content)?e.headers["Content-Type"]="application/octet-stream":e.headers["Content-Type"]="text/plain;charset=UTF-8");try{o=await this._fetchType(e.url,{body:e.content,cache:"no-cache",credentials:!0===e.withCredentials?"include":"same-origin",headers:{"X-Requested-With":"XMLHttpRequest",...e.headers},method:e.method,mode:"cors",redirect:"follow",signal:t.signal})}catch(e){if(n)throw n;throw this._logger.log(vt.Warning,`Error from HTTP request. ${e}.`),e}finally{r&&clearTimeout(r),e.abortSignal&&(e.abortSignal.onabort=null)}if(!o.ok){const e=await en(o,"text");throw new Nt(e||o.statusText,o.status)}const s=en(o,e.responseType),i=await s;return new Yt(o.status,o.statusText,i)}getCookieString(e){return""}}function en(e,t){let n;switch(t){case"arraybuffer":n=e.arrayBuffer();break;case"text":default:n=e.text();break;case"blob":case"document":case"json":throw new Error(`${t} is not supported.`)}return n}class tn extends Gt{constructor(e){super(),this._logger=e}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new Mt):e.method?e.url?new Promise(((t,n)=>{const o=new XMLHttpRequest;o.open(e.method,e.url,!0),o.withCredentials=void 0===e.withCredentials||e.withCredentials,o.setRequestHeader("X-Requested-With","XMLHttpRequest"),""===e.content&&(e.content=void 0),e.content&&(Et(e.content)?o.setRequestHeader("Content-Type","application/octet-stream"):o.setRequestHeader("Content-Type","text/plain;charset=UTF-8"));const r=e.headers;r&&Object.keys(r).forEach((e=>{o.setRequestHeader(e,r[e])})),e.responseType&&(o.responseType=e.responseType),e.abortSignal&&(e.abortSignal.onabort=()=>{o.abort(),n(new Mt)}),e.timeout&&(o.timeout=e.timeout),o.onload=()=>{e.abortSignal&&(e.abortSignal.onabort=null),o.status>=200&&o.status<300?t(new Yt(o.status,o.statusText,o.response||o.responseText)):n(new Nt(o.response||o.responseText||o.statusText,o.status))},o.onerror=()=>{this._logger.log(vt.Warning,`Error from HTTP request. ${o.status}: ${o.statusText}.`),n(new Nt(o.statusText,o.status))},o.ontimeout=()=>{this._logger.log(vt.Warning,"Timeout from HTTP request."),n(new Ut)},o.send(e.content)})):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}}class nn extends Gt{constructor(e){if(super(),"undefined"!=typeof fetch)this._httpClient=new Zt(e);else{if("undefined"==typeof XMLHttpRequest)throw new Error("No usable HttpClient found.");this._httpClient=new tn(e)}}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new Mt):e.method?e.url?this._httpClient.send(e):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}getCookieString(e){return this._httpClient.getCookieString(e)}}var on,rn;!function(e){e[e.None=0]="None",e[e.WebSockets=1]="WebSockets",e[e.ServerSentEvents=2]="ServerSentEvents",e[e.LongPolling=4]="LongPolling"}(on||(on={})),function(e){e[e.Text=1]="Text",e[e.Binary=2]="Binary"}(rn||(rn={}));class sn{constructor(){this._isAborted=!1,this.onabort=null}abort(){this._isAborted||(this._isAborted=!0,this.onabort&&this.onabort())}get signal(){return this}get aborted(){return this._isAborted}}class an{get pollAborted(){return this._pollAbort.aborted}constructor(e,t,n){this._httpClient=e,this._logger=t,this._pollAbort=new sn,this._options=n,this._running=!1,this.onreceive=null,this.onclose=null}async connect(e,t){if(_t.isRequired(e,"url"),_t.isRequired(t,"transferFormat"),_t.isIn(t,rn,"transferFormat"),this._url=e,this._logger.log(vt.Trace,"(LongPolling transport) Connecting."),t===rn.Binary&&"undefined"!=typeof XMLHttpRequest&&"string"!=typeof(new XMLHttpRequest).responseType)throw new Error("Binary protocols over XmlHttpRequest not implementing advanced features are not supported.");const[n,o]=Tt(),r={[n]:o,...this._options.headers},s={abortSignal:this._pollAbort.signal,headers:r,timeout:1e5,withCredentials:this._options.withCredentials};t===rn.Binary&&(s.responseType="arraybuffer");const i=`${e}&_=${Date.now()}`;this._logger.log(vt.Trace,`(LongPolling transport) polling: ${i}.`);const a=await this._httpClient.get(i,s);200!==a.statusCode?(this._logger.log(vt.Error,`(LongPolling transport) Unexpected response code: ${a.statusCode}.`),this._closeError=new Nt(a.statusText||"",a.statusCode),this._running=!1):this._running=!0,this._receiving=this._poll(this._url,s)}async _poll(e,t){try{for(;this._running;)try{const n=`${e}&_=${Date.now()}`;this._logger.log(vt.Trace,`(LongPolling transport) polling: ${n}.`);const o=await this._httpClient.get(n,t);204===o.statusCode?(this._logger.log(vt.Information,"(LongPolling transport) Poll terminated by server."),this._running=!1):200!==o.statusCode?(this._logger.log(vt.Error,`(LongPolling transport) Unexpected response code: ${o.statusCode}.`),this._closeError=new Nt(o.statusText||"",o.statusCode),this._running=!1):o.content?(this._logger.log(vt.Trace,`(LongPolling transport) data received. ${St(o.content,this._options.logMessageContent)}.`),this.onreceive&&this.onreceive(o.content)):this._logger.log(vt.Trace,"(LongPolling transport) Poll timed out, reissuing.")}catch(e){this._running?e instanceof Ut?this._logger.log(vt.Trace,"(LongPolling transport) Poll timed out, reissuing."):(this._closeError=e,this._running=!1):this._logger.log(vt.Trace,`(LongPolling transport) Poll errored after shutdown: ${e.message}`)}}finally{this._logger.log(vt.Trace,"(LongPolling transport) Polling complete."),this.pollAborted||this._raiseOnClose()}}async send(e){return this._running?Ct(this._logger,"LongPolling",this._httpClient,this._url,e,this._options):Promise.reject(new Error("Cannot send until the transport is connected"))}async stop(){this._logger.log(vt.Trace,"(LongPolling transport) Stopping polling."),this._running=!1,this._pollAbort.abort();try{await this._receiving,this._logger.log(vt.Trace,`(LongPolling transport) sending DELETE request to ${this._url}.`);const e={},[t,n]=Tt();e[t]=n;const o={headers:{...e,...this._options.headers},timeout:this._options.timeout,withCredentials:this._options.withCredentials};let r;try{await this._httpClient.delete(this._url,o)}catch(e){r=e}r?r instanceof Nt&&(404===r.statusCode?this._logger.log(vt.Trace,"(LongPolling transport) A 404 response was returned from sending a DELETE request."):this._logger.log(vt.Trace,`(LongPolling transport) Error sending a DELETE request: ${r}`)):this._logger.log(vt.Trace,"(LongPolling transport) DELETE request accepted.")}finally{this._logger.log(vt.Trace,"(LongPolling transport) Stop finished."),this._raiseOnClose()}}_raiseOnClose(){if(this.onclose){let e="(LongPolling transport) Firing onclose event.";this._closeError&&(e+=" Error: "+this._closeError),this._logger.log(vt.Trace,e),this.onclose(this._closeError)}}}class cn{constructor(e,t,n,o){this._httpClient=e,this._accessToken=t,this._logger=n,this._options=o,this.onreceive=null,this.onclose=null}async connect(e,t){return _t.isRequired(e,"url"),_t.isRequired(t,"transferFormat"),_t.isIn(t,rn,"transferFormat"),this._logger.log(vt.Trace,"(SSE transport) Connecting."),this._url=e,this._accessToken&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(this._accessToken)}`),new Promise(((n,o)=>{let r,s=!1;if(t===rn.Text){if(bt.isBrowser||bt.isWebWorker)r=new this._options.EventSource(e,{withCredentials:this._options.withCredentials});else{const t=this._httpClient.getCookieString(e),n={};n.Cookie=t;const[o,s]=Tt();n[o]=s,r=new this._options.EventSource(e,{withCredentials:this._options.withCredentials,headers:{...n,...this._options.headers}})}try{r.onmessage=e=>{if(this.onreceive)try{this._logger.log(vt.Trace,`(SSE transport) data received. ${St(e.data,this._options.logMessageContent)}.`),this.onreceive(e.data)}catch(e){return void this._close(e)}},r.onerror=e=>{s?this._close():o(new Error("EventSource failed to connect. The connection could not be found on the server, either the connection ID is not present on the server, or a proxy is refusing/buffering the connection. If you have multiple servers check that sticky sessions are enabled."))},r.onopen=()=>{this._logger.log(vt.Information,`SSE connected to ${this._url}`),this._eventSource=r,s=!0,n()}}catch(e){return void o(e)}}else o(new Error("The Server-Sent Events transport only supports the 'Text' transfer format"))}))}async send(e){return this._eventSource?Ct(this._logger,"SSE",this._httpClient,this._url,e,this._options):Promise.reject(new Error("Cannot send until the transport is connected"))}stop(){return this._close(),Promise.resolve()}_close(e){this._eventSource&&(this._eventSource.close(),this._eventSource=void 0,this.onclose&&this.onclose(e))}}class ln{constructor(e,t,n,o,r,s){this._logger=n,this._accessTokenFactory=t,this._logMessageContent=o,this._webSocketConstructor=r,this._httpClient=e,this.onreceive=null,this.onclose=null,this._headers=s}async connect(e,t){let n;return _t.isRequired(e,"url"),_t.isRequired(t,"transferFormat"),_t.isIn(t,rn,"transferFormat"),this._logger.log(vt.Trace,"(WebSockets transport) Connecting."),this._accessTokenFactory&&(n=await this._accessTokenFactory()),new Promise(((o,r)=>{let s;e=e.replace(/^http/,"ws");const i=this._httpClient.getCookieString(e);let a=!1;if(bt.isReactNative){const t={},[o,r]=Tt();t[o]=r,n&&(t[Xt.Authorization]=`Bearer ${n}`),i&&(t[Xt.Cookie]=i),s=new this._webSocketConstructor(e,void 0,{headers:{...t,...this._headers}})}else n&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(n)}`);s||(s=new this._webSocketConstructor(e)),t===rn.Binary&&(s.binaryType="arraybuffer"),s.onopen=t=>{this._logger.log(vt.Information,`WebSocket connected to ${e}.`),this._webSocket=s,a=!0,o()},s.onerror=e=>{let t=null;t="undefined"!=typeof ErrorEvent&&e instanceof ErrorEvent?e.error:"There was an error with the transport",this._logger.log(vt.Information,`(WebSockets transport) ${t}.`)},s.onmessage=e=>{if(this._logger.log(vt.Trace,`(WebSockets transport) data received. ${St(e.data,this._logMessageContent)}.`),this.onreceive)try{this.onreceive(e.data)}catch(e){return void this._close(e)}},s.onclose=e=>{if(a)this._close(e);else{let t=null;t="undefined"!=typeof ErrorEvent&&e instanceof ErrorEvent?e.error:"WebSocket failed to connect. The connection could not be found on the server, either the endpoint may not be a SignalR endpoint, the connection ID is not present on the server, or there is a proxy blocking WebSockets. If you have multiple servers check that sticky sessions are enabled.",r(new Error(t))}}}))}send(e){return this._webSocket&&this._webSocket.readyState===this._webSocketConstructor.OPEN?(this._logger.log(vt.Trace,`(WebSockets transport) sending data. ${St(e,this._logMessageContent)}.`),this._webSocket.send(e),Promise.resolve()):Promise.reject("WebSocket is not in the OPEN state")}stop(){return this._webSocket&&this._close(void 0),Promise.resolve()}_close(e){this._webSocket&&(this._webSocket.onclose=()=>{},this._webSocket.onmessage=()=>{},this._webSocket.onerror=()=>{},this._webSocket.close(),this._webSocket=void 0),this._logger.log(vt.Trace,"(WebSockets transport) socket closed."),this.onclose&&(!this._isCloseEvent(e)||!1!==e.wasClean&&1e3===e.code?e instanceof Error?this.onclose(e):this.onclose():this.onclose(new Error(`WebSocket closed with status code: ${e.code} (${e.reason||"no reason given"}).`)))}_isCloseEvent(e){return e&&"boolean"==typeof e.wasClean&&"number"==typeof e.code}}class hn{constructor(e,t={}){if(this._stopPromiseResolver=()=>{},this.features={},this._negotiateVersion=1,_t.isRequired(e,"url"),this._logger=function(e){return void 0===e?new kt(vt.Information):null===e?yt.instance:void 0!==e.log?e:new kt(e)}(t.logger),this.baseUrl=this._resolveUrl(e),(t=t||{}).logMessageContent=void 0!==t.logMessageContent&&t.logMessageContent,"boolean"!=typeof t.withCredentials&&void 0!==t.withCredentials)throw new Error("withCredentials option was not a 'boolean' or 'undefined' value");t.withCredentials=void 0===t.withCredentials||t.withCredentials,t.timeout=void 0===t.timeout?1e5:t.timeout,"undefined"==typeof WebSocket||t.WebSocket||(t.WebSocket=WebSocket),"undefined"==typeof EventSource||t.EventSource||(t.EventSource=EventSource),this._httpClient=new Qt(t.httpClient||new nn(this._logger),t.accessTokenFactory),this._connectionState="Disconnected",this._connectionStarted=!1,this._options=t,this.onreceive=null,this.onclose=null}async start(e){if(e=e||rn.Binary,_t.isIn(e,rn,"transferFormat"),this._logger.log(vt.Debug,`Starting connection with transfer format '${rn[e]}'.`),"Disconnected"!==this._connectionState)return Promise.reject(new Error("Cannot start an HttpConnection that is not in the 'Disconnected' state."));if(this._connectionState="Connecting",this._startInternalPromise=this._startInternal(e),await this._startInternalPromise,"Disconnecting"===this._connectionState){const e="Failed to start the HttpConnection before stop() was called.";return this._logger.log(vt.Error,e),await this._stopPromise,Promise.reject(new Mt(e))}if("Connected"!==this._connectionState){const e="HttpConnection.startInternal completed gracefully but didn't enter the connection into the connected state!";return this._logger.log(vt.Error,e),Promise.reject(new Mt(e))}this._connectionStarted=!0}send(e){return"Connected"!==this._connectionState?Promise.reject(new Error("Cannot send data if the connection is not in the 'Connected' State.")):(this._sendQueue||(this._sendQueue=new dn(this.transport)),this._sendQueue.send(e))}async stop(e){return"Disconnected"===this._connectionState?(this._logger.log(vt.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnected state.`),Promise.resolve()):"Disconnecting"===this._connectionState?(this._logger.log(vt.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnecting state.`),this._stopPromise):(this._connectionState="Disconnecting",this._stopPromise=new Promise((e=>{this._stopPromiseResolver=e})),await this._stopInternal(e),void await this._stopPromise)}async _stopInternal(e){this._stopError=e;try{await this._startInternalPromise}catch(e){}if(this.transport){try{await this.transport.stop()}catch(e){this._logger.log(vt.Error,`HttpConnection.transport.stop() threw error '${e}'.`),this._stopConnection()}this.transport=void 0}else this._logger.log(vt.Debug,"HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.")}async _startInternal(e){let t=this.baseUrl;this._accessTokenFactory=this._options.accessTokenFactory,this._httpClient._accessTokenFactory=this._accessTokenFactory;try{if(this._options.skipNegotiation){if(this._options.transport!==on.WebSockets)throw new Error("Negotiation can only be skipped when using the WebSocket transport directly.");this.transport=this._constructTransport(on.WebSockets),await this._startTransport(t,e)}else{let n=null,o=0;do{if(n=await this._getNegotiationResponse(t),"Disconnecting"===this._connectionState||"Disconnected"===this._connectionState)throw new Mt("The connection was stopped during negotiation.");if(n.error)throw new Error(n.error);if(n.ProtocolVersion)throw new Error("Detected a connection attempt to an ASP.NET SignalR Server. This client only supports connecting to an ASP.NET Core SignalR Server. See https://aka.ms/signalr-core-differences for details.");if(n.url&&(t=n.url),n.accessToken){const e=n.accessToken;this._accessTokenFactory=()=>e,this._httpClient._accessToken=e,this._httpClient._accessTokenFactory=void 0}o++}while(n.url&&o<100);if(100===o&&n.url)throw new Error("Negotiate redirection limit exceeded.");await this._createTransport(t,this._options.transport,n,e)}this.transport instanceof an&&(this.features.inherentKeepAlive=!0),"Connecting"===this._connectionState&&(this._logger.log(vt.Debug,"The HttpConnection connected successfully."),this._connectionState="Connected")}catch(e){return this._logger.log(vt.Error,"Failed to start the connection: "+e),this._connectionState="Disconnected",this.transport=void 0,this._stopPromiseResolver(),Promise.reject(e)}}async _getNegotiationResponse(e){const t={},[n,o]=Tt();t[n]=o;const r=this._resolveNegotiateUrl(e);this._logger.log(vt.Debug,`Sending negotiation request: ${r}.`);try{const e=await this._httpClient.post(r,{content:"",headers:{...t,...this._options.headers},timeout:this._options.timeout,withCredentials:this._options.withCredentials});if(200!==e.statusCode)return Promise.reject(new Error(`Unexpected status code returned from negotiate '${e.statusCode}'`));const n=JSON.parse(e.content);return(!n.negotiateVersion||n.negotiateVersion<1)&&(n.connectionToken=n.connectionId),n.useStatefulReconnect&&!0!==this._options._useStatefulReconnect?Promise.reject(new Ot("Client didn't negotiate Stateful Reconnect but the server did.")):n}catch(e){let t="Failed to complete negotiation with the server: "+e;return e instanceof Nt&&404===e.statusCode&&(t+=" Either this is not a SignalR endpoint or there is a proxy blocking the connection."),this._logger.log(vt.Error,t),Promise.reject(new Ot(t))}}_createConnectUrl(e,t){return t?e+(-1===e.indexOf("?")?"?":"&")+`id=${t}`:e}async _createTransport(e,t,n,o){let r=this._createConnectUrl(e,n.connectionToken);if(this._isITransport(t))return this._logger.log(vt.Debug,"Connection was provided an instance of ITransport, using that directly."),this.transport=t,await this._startTransport(r,o),void(this.connectionId=n.connectionId);const s=[],i=n.availableTransports||[];let a=n;for(const n of i){const i=this._resolveTransportOrError(n,t,o,!0===(null==a?void 0:a.useStatefulReconnect));if(i instanceof Error)s.push(`${n.transport} failed:`),s.push(i);else if(this._isITransport(i)){if(this.transport=i,!a){try{a=await this._getNegotiationResponse(e)}catch(e){return Promise.reject(e)}r=this._createConnectUrl(e,a.connectionToken)}try{return await this._startTransport(r,o),void(this.connectionId=a.connectionId)}catch(e){if(this._logger.log(vt.Error,`Failed to start the transport '${n.transport}': ${e}`),a=void 0,s.push(new $t(`${n.transport} failed: ${e}`,on[n.transport])),"Connecting"!==this._connectionState){const e="Failed to select transport before stop() was called.";return this._logger.log(vt.Debug,e),Promise.reject(new Mt(e))}}}}return s.length>0?Promise.reject(new Ft(`Unable to connect to the server with any of the available transports. ${s.join(" ")}`,s)):Promise.reject(new Error("None of the transports supported by the client are supported by the server."))}_constructTransport(e){switch(e){case on.WebSockets:if(!this._options.WebSocket)throw new Error("'WebSocket' is not supported in your environment.");return new ln(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent,this._options.WebSocket,this._options.headers||{});case on.ServerSentEvents:if(!this._options.EventSource)throw new Error("'EventSource' is not supported in your environment.");return new cn(this._httpClient,this._httpClient._accessToken,this._logger,this._options);case on.LongPolling:return new an(this._httpClient,this._logger,this._options);default:throw new Error(`Unknown transport: ${e}.`)}}_startTransport(e,t){return this.transport.onreceive=this.onreceive,this.features.reconnect?this.transport.onclose=async n=>{let o=!1;if(this.features.reconnect){try{this.features.disconnected(),await this.transport.connect(e,t),await this.features.resend()}catch{o=!0}o&&this._stopConnection(n)}else this._stopConnection(n)}:this.transport.onclose=e=>this._stopConnection(e),this.transport.connect(e,t)}_resolveTransportOrError(e,t,n,o){const r=on[e.transport];if(null==r)return this._logger.log(vt.Debug,`Skipping transport '${e.transport}' because it is not supported by this client.`),new Error(`Skipping transport '${e.transport}' because it is not supported by this client.`);if(!function(e,t){return!e||0!=(t&e)}(t,r))return this._logger.log(vt.Debug,`Skipping transport '${on[r]}' because it was disabled by the client.`),new Lt(`'${on[r]}' is disabled by the client.`,r);if(!(e.transferFormats.map((e=>rn[e])).indexOf(n)>=0))return this._logger.log(vt.Debug,`Skipping transport '${on[r]}' because it does not support the requested transfer format '${rn[n]}'.`),new Error(`'${on[r]}' does not support ${rn[n]}.`);if(r===on.WebSockets&&!this._options.WebSocket||r===on.ServerSentEvents&&!this._options.EventSource)return this._logger.log(vt.Debug,`Skipping transport '${on[r]}' because it is not supported in your environment.'`),new Bt(`'${on[r]}' is not supported in your environment.`,r);this._logger.log(vt.Debug,`Selecting transport '${on[r]}'.`);try{return this.features.reconnect=r===on.WebSockets?o:void 0,this._constructTransport(r)}catch(e){return e}}_isITransport(e){return e&&"object"==typeof e&&"connect"in e}_stopConnection(e){if(this._logger.log(vt.Debug,`HttpConnection.stopConnection(${e}) called while in state ${this._connectionState}.`),this.transport=void 0,e=this._stopError||e,this._stopError=void 0,"Disconnected"!==this._connectionState){if("Connecting"===this._connectionState)throw this._logger.log(vt.Warning,`Call to HttpConnection.stopConnection(${e}) was ignored because the connection is still in the connecting state.`),new Error(`HttpConnection.stopConnection(${e}) was called while the connection is still in the connecting state.`);if("Disconnecting"===this._connectionState&&this._stopPromiseResolver(),e?this._logger.log(vt.Error,`Connection disconnected with error '${e}'.`):this._logger.log(vt.Information,"Connection disconnected."),this._sendQueue&&(this._sendQueue.stop().catch((e=>{this._logger.log(vt.Error,`TransportSendQueue.stop() threw error '${e}'.`)})),this._sendQueue=void 0),this.connectionId=void 0,this._connectionState="Disconnected",this._connectionStarted){this._connectionStarted=!1;try{this.onclose&&this.onclose(e)}catch(t){this._logger.log(vt.Error,`HttpConnection.onclose(${e}) threw error '${t}'.`)}}}else this._logger.log(vt.Debug,`Call to HttpConnection.stopConnection(${e}) was ignored because the connection is already in the disconnected state.`)}_resolveUrl(e){if(0===e.lastIndexOf("https://",0)||0===e.lastIndexOf("http://",0))return e;if(!bt.isBrowser)throw new Error(`Cannot resolve '${e}'.`);const t=window.document.createElement("a");return t.href=e,this._logger.log(vt.Information,`Normalizing '${e}' to '${t.href}'.`),t.href}_resolveNegotiateUrl(e){const t=new URL(e);t.pathname.endsWith("/")?t.pathname+="negotiate":t.pathname+="/negotiate";const n=new URLSearchParams(t.searchParams);return n.has("negotiateVersion")||n.append("negotiateVersion",this._negotiateVersion.toString()),n.has("useStatefulReconnect")?"true"===n.get("useStatefulReconnect")&&(this._options._useStatefulReconnect=!0):!0===this._options._useStatefulReconnect&&n.append("useStatefulReconnect","true"),t.search=n.toString(),t.toString()}}class dn{constructor(e){this._transport=e,this._buffer=[],this._executing=!0,this._sendBufferedData=new un,this._transportResult=new un,this._sendLoopPromise=this._sendLoop()}send(e){return this._bufferData(e),this._transportResult||(this._transportResult=new un),this._transportResult.promise}stop(){return this._executing=!1,this._sendBufferedData.resolve(),this._sendLoopPromise}_bufferData(e){if(this._buffer.length&&typeof this._buffer[0]!=typeof e)throw new Error(`Expected data to be of type ${typeof this._buffer} but was of type ${typeof e}`);this._buffer.push(e),this._sendBufferedData.resolve()}async _sendLoop(){for(;;){if(await this._sendBufferedData.promise,!this._executing){this._transportResult&&this._transportResult.reject("Connection stopped.");break}this._sendBufferedData=new un;const e=this._transportResult;this._transportResult=void 0;const t="string"==typeof this._buffer[0]?this._buffer.join(""):dn._concatBuffers(this._buffer);this._buffer.length=0;try{await this._transport.send(t),e.resolve()}catch(t){e.reject(t)}}}static _concatBuffers(e){const t=e.map((e=>e.byteLength)).reduce(((e,t)=>e+t)),n=new Uint8Array(t);let o=0;for(const t of e)n.set(new Uint8Array(t),o),o+=t.byteLength;return n.buffer}}class un{constructor(){this.promise=new Promise(((e,t)=>[this._resolver,this._rejecter]=[e,t]))}resolve(){this._resolver()}reject(e){this._rejecter(e)}}class pn{constructor(){this.name="json",this.version=2,this.transferFormat=rn.Text}parseMessages(e,t){if("string"!=typeof e)throw new Error("Invalid input for JSON hub protocol. Expected a string.");if(!e)return[];null===t&&(t=yt.instance);const n=mt.parse(e),o=[];for(const e of n){const n=JSON.parse(e);if("number"!=typeof n.type)throw new Error("Invalid payload.");switch(n.type){case Ht.Invocation:this._isInvocationMessage(n);break;case Ht.StreamItem:this._isStreamItemMessage(n);break;case Ht.Completion:this._isCompletionMessage(n);break;case Ht.Ping:case Ht.Close:break;case Ht.Ack:this._isAckMessage(n);break;case Ht.Sequence:this._isSequenceMessage(n);break;default:t.log(vt.Information,"Unknown message type '"+n.type+"' ignored.");continue}o.push(n)}return o}writeMessage(e){return mt.write(JSON.stringify(e))}_isInvocationMessage(e){this._assertNotEmptyString(e.target,"Invalid payload for Invocation message."),void 0!==e.invocationId&&this._assertNotEmptyString(e.invocationId,"Invalid payload for Invocation message.")}_isStreamItemMessage(e){if(this._assertNotEmptyString(e.invocationId,"Invalid payload for StreamItem message."),void 0===e.item)throw new Error("Invalid payload for StreamItem message.")}_isCompletionMessage(e){if(e.result&&e.error)throw new Error("Invalid payload for Completion message.");!e.result&&e.error&&this._assertNotEmptyString(e.error,"Invalid payload for Completion message."),this._assertNotEmptyString(e.invocationId,"Invalid payload for Completion message.")}_isAckMessage(e){if("number"!=typeof e.sequenceId)throw new Error("Invalid SequenceId for Ack message.")}_isSequenceMessage(e){if("number"!=typeof e.sequenceId)throw new Error("Invalid SequenceId for Sequence message.")}_assertNotEmptyString(e,t){if("string"!=typeof e||""===e)throw new Error(t)}}const fn={trace:vt.Trace,debug:vt.Debug,info:vt.Information,information:vt.Information,warn:vt.Warning,warning:vt.Warning,error:vt.Error,critical:vt.Critical,none:vt.None};class gn{configureLogging(e){if(_t.isRequired(e,"logging"),function(e){return void 0!==e.log}(e))this.logger=e;else if("string"==typeof e){const t=function(e){const t=fn[e.toLowerCase()];if(void 0!==t)return t;throw new Error(`Unknown log level: ${e}`)}(e);this.logger=new kt(t)}else this.logger=new kt(e);return this}withUrl(e,t){return _t.isRequired(e,"url"),_t.isNotEmpty(e,"url"),this.url=e,this.httpConnectionOptions="object"==typeof t?{...this.httpConnectionOptions,...t}:{...this.httpConnectionOptions,transport:t},this}withHubProtocol(e){return _t.isRequired(e,"protocol"),this.protocol=e,this}withAutomaticReconnect(e){if(this.reconnectPolicy)throw new Error("A reconnectPolicy has already been set.");return e?Array.isArray(e)?this.reconnectPolicy=new Vt(e):this.reconnectPolicy=e:this.reconnectPolicy=new Vt,this}withServerTimeout(e){return _t.isRequired(e,"milliseconds"),this._serverTimeoutInMilliseconds=e,this}withKeepAliveInterval(e){return _t.isRequired(e,"milliseconds"),this._keepAliveIntervalInMilliseconds=e,this}withStatefulReconnect(e){return void 0===this.httpConnectionOptions&&(this.httpConnectionOptions={}),this.httpConnectionOptions._useStatefulReconnect=!0,this._statefulReconnectBufferSize=null==e?void 0:e.bufferSize,this}build(){const e=this.httpConnectionOptions||{};if(void 0===e.logger&&(e.logger=this.logger),!this.url)throw new Error("The 'HubConnectionBuilder.withUrl' method must be called before building the connection.");const t=new hn(this.url,e);return Jt.create(t,this.logger||yt.instance,this.protocol||new pn,this.reconnectPolicy,this._serverTimeoutInMilliseconds,this._keepAliveIntervalInMilliseconds,this._statefulReconnectBufferSize)}}var mn;!function(e){e[e.Default=0]="Default",e[e.Server=1]="Server",e[e.WebAssembly=2]="WebAssembly",e[e.WebView=3]="WebView"}(mn||(mn={}));var vn,yn,wn,_n=4294967295;function bn(e,t,n){var o=Math.floor(n/4294967296),r=n;e.setUint32(t,o),e.setUint32(t+4,r)}function Sn(e,t){return 4294967296*e.getInt32(t)+e.getUint32(t+4)}var En=("undefined"==typeof process||"never"!==(null===(vn=null===process||void 0===process?void 0:process.env)||void 0===vn?void 0:vn.TEXT_ENCODING))&&"undefined"!=typeof TextEncoder&&"undefined"!=typeof TextDecoder;function Cn(e){for(var t=e.length,n=0,o=0;o=55296&&r<=56319&&o65535&&(h-=65536,s.push(h>>>10&1023|55296),h=56320|1023&h),s.push(h)}else s.push(a);s.length>=4096&&(i+=String.fromCharCode.apply(String,s),s.length=0)}return s.length>0&&(i+=String.fromCharCode.apply(String,s)),i}var xn,Rn=En?new TextDecoder:null,Pn=En?"undefined"!=typeof process&&"force"!==(null===(wn=null===process||void 0===process?void 0:process.env)||void 0===wn?void 0:wn.TEXT_DECODER)?200:0:_n,An=function(e,t){this.type=e,this.data=t},Nn=(xn=function(e,t){return xn=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},xn(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function n(){this.constructor=e}xn(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),Un=function(e){function t(n){var o=e.call(this,n)||this,r=Object.create(t.prototype);return Object.setPrototypeOf(o,r),Object.defineProperty(o,"name",{configurable:!0,enumerable:!1,value:t.name}),o}return Nn(t,e),t}(Error),Mn={type:-1,encode:function(e){var t,n,o,r;return e instanceof Date?function(e){var t,n=e.sec,o=e.nsec;if(n>=0&&o>=0&&n<=17179869183){if(0===o&&n<=4294967295){var r=new Uint8Array(4);return(t=new DataView(r.buffer)).setUint32(0,n),r}var s=n/4294967296,i=4294967295&n;return r=new Uint8Array(8),(t=new DataView(r.buffer)).setUint32(0,o<<2|3&s),t.setUint32(4,i),r}return r=new Uint8Array(12),(t=new DataView(r.buffer)).setUint32(0,o),bn(t,4,n),r}((o=1e6*((t=e.getTime())-1e3*(n=Math.floor(t/1e3))),{sec:n+(r=Math.floor(o/1e9)),nsec:o-1e9*r})):null},decode:function(e){var t=function(e){var t=new DataView(e.buffer,e.byteOffset,e.byteLength);switch(e.byteLength){case 4:return{sec:t.getUint32(0),nsec:0};case 8:var n=t.getUint32(0);return{sec:4294967296*(3&n)+t.getUint32(4),nsec:n>>>2};case 12:return{sec:Sn(t,4),nsec:t.getUint32(0)};default:throw new Un("Unrecognized data size for timestamp (expected 4, 8, or 12): ".concat(e.length))}}(e);return new Date(1e3*t.sec+t.nsec/1e6)}},Bn=function(){function e(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(Mn)}return e.prototype.register=function(e){var t=e.type,n=e.encode,o=e.decode;if(t>=0)this.encoders[t]=n,this.decoders[t]=o;else{var r=1+t;this.builtInEncoders[r]=n,this.builtInDecoders[r]=o}},e.prototype.tryToEncode=function(e,t){for(var n=0;nthis.maxDepth)throw new Error("Too deep objects in depth ".concat(t));null==e?this.encodeNil():"boolean"==typeof e?this.encodeBoolean(e):"number"==typeof e?this.encodeNumber(e):"string"==typeof e?this.encodeString(e):this.encodeObject(e,t)},e.prototype.ensureBufferSizeToWrite=function(e){var t=this.pos+e;this.view.byteLength=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):(this.writeU8(211),this.writeI64(e)):this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))},e.prototype.writeStringHeader=function(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else{if(!(e<4294967296))throw new Error("Too long string: ".concat(e," bytes in UTF-8"));this.writeU8(219),this.writeU32(e)}},e.prototype.encodeString=function(e){if(e.length>kn){var t=Cn(e);this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),Tn(e,this.bytes,this.pos),this.pos+=t}else t=Cn(e),this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),function(e,t,n){for(var o=e.length,r=n,s=0;s>6&31|192;else{if(i>=55296&&i<=56319&&s>12&15|224,t[r++]=i>>6&63|128):(t[r++]=i>>18&7|240,t[r++]=i>>12&63|128,t[r++]=i>>6&63|128)}t[r++]=63&i|128}else t[r++]=i}}(e,this.bytes,this.pos),this.pos+=t},e.prototype.encodeObject=function(e,t){var n=this.extensionCodec.tryToEncode(e,this.context);if(null!=n)this.encodeExtension(n);else if(Array.isArray(e))this.encodeArray(e,t);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else{if("object"!=typeof e)throw new Error("Unrecognized object: ".concat(Object.prototype.toString.apply(e)));this.encodeMap(e,t)}},e.prototype.encodeBinary=function(e){var t=e.byteLength;if(t<256)this.writeU8(196),this.writeU8(t);else if(t<65536)this.writeU8(197),this.writeU16(t);else{if(!(t<4294967296))throw new Error("Too large binary: ".concat(t));this.writeU8(198),this.writeU32(t)}var n=Ln(e);this.writeU8a(n)},e.prototype.encodeArray=function(e,t){var n=e.length;if(n<16)this.writeU8(144+n);else if(n<65536)this.writeU8(220),this.writeU16(n);else{if(!(n<4294967296))throw new Error("Too large array: ".concat(n));this.writeU8(221),this.writeU32(n)}for(var o=0,r=e;o0&&e<=this.maxKeyLength},e.prototype.find=function(e,t,n){e:for(var o=0,r=this.caches[n-1];o=this.maxLengthPerKey?n[Math.random()*n.length|0]=o:n.push(o)},e.prototype.decode=function(e,t,n){var o=this.find(e,t,n);if(null!=o)return this.hit++,o;this.miss++;var r=Dn(e,t,n),s=Uint8Array.prototype.slice.call(e,t,t+n);return this.store(s,r),r},e}(),Hn=function(e,t){var n,o,r,s,i={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(s){return function(a){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;i;)try{if(n=1,o&&(r=2&s[0]?o.return:s[0]?o.throw||((r=o.return)&&r.call(o),0):o.next)&&!(r=r.call(o,s[1])).done)return r;switch(o=0,r&&(s=[2&s[0],r.value]),s[0]){case 0:case 1:r=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,o=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!((r=(r=i.trys).length>0&&r[r.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!r||s[1]>r[0]&&s[1]=e},e.prototype.createExtraByteError=function(e){var t=this.view,n=this.pos;return new RangeError("Extra ".concat(t.byteLength-n," of ").concat(t.byteLength," byte(s) found at buffer[").concat(e,"]"))},e.prototype.decode=function(e){this.reinitializeState(),this.setBuffer(e);var t=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return t},e.prototype.decodeMulti=function(e){return Hn(this,(function(t){switch(t.label){case 0:this.reinitializeState(),this.setBuffer(e),t.label=1;case 1:return this.hasRemaining(1)?[4,this.doDecodeSync()]:[3,3];case 2:return t.sent(),[3,1];case 3:return[2]}}))},e.prototype.decodeAsync=function(e){var t,n,o,r,s,i,a;return s=this,void 0,a=function(){var s,i,a,c,l,h,d,u;return Hn(this,(function(p){switch(p.label){case 0:s=!1,p.label=1;case 1:p.trys.push([1,6,7,12]),t=jn(e),p.label=2;case 2:return[4,t.next()];case 3:if((n=p.sent()).done)return[3,5];if(a=n.value,s)throw this.createExtraByteError(this.totalPos);this.appendBuffer(a);try{i=this.doDecodeSync(),s=!0}catch(e){if(!(e instanceof Jn))throw e}this.totalPos+=this.pos,p.label=4;case 4:return[3,2];case 5:return[3,12];case 6:return c=p.sent(),o={error:c},[3,12];case 7:return p.trys.push([7,,10,11]),n&&!n.done&&(r=t.return)?[4,r.call(t)]:[3,9];case 8:p.sent(),p.label=9;case 9:return[3,11];case 10:if(o)throw o.error;return[7];case 11:return[7];case 12:if(s){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return[2,i]}throw h=(l=this).headByte,d=l.pos,u=l.totalPos,new RangeError("Insufficient data in parsing ".concat(On(h)," at ").concat(u," (").concat(d," in the current buffer)"))}}))},new((i=void 0)||(i=Promise))((function(e,t){function n(e){try{r(a.next(e))}catch(e){t(e)}}function o(e){try{r(a.throw(e))}catch(e){t(e)}}function r(t){var r;t.done?e(t.value):(r=t.value,r instanceof i?r:new i((function(e){e(r)}))).then(n,o)}r((a=a.apply(s,[])).next())}))},e.prototype.decodeArrayStream=function(e){return this.decodeMultiAsync(e,!0)},e.prototype.decodeStream=function(e){return this.decodeMultiAsync(e,!1)},e.prototype.decodeMultiAsync=function(e,t){return function(n,o,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var s,i=function(){var n,o,r,s,i,a,c,l,h;return Hn(this,(function(d){switch(d.label){case 0:n=t,o=-1,d.label=1;case 1:d.trys.push([1,13,14,19]),r=jn(e),d.label=2;case 2:return[4,Wn(r.next())];case 3:if((s=d.sent()).done)return[3,12];if(i=s.value,t&&0===o)throw this.createExtraByteError(this.totalPos);this.appendBuffer(i),n&&(o=this.readArraySize(),n=!1,this.complete()),d.label=4;case 4:d.trys.push([4,9,,10]),d.label=5;case 5:return[4,Wn(this.doDecodeSync())];case 6:return[4,d.sent()];case 7:return d.sent(),0==--o?[3,8]:[3,5];case 8:return[3,10];case 9:if(!((a=d.sent())instanceof Jn))throw a;return[3,10];case 10:this.totalPos+=this.pos,d.label=11;case 11:return[3,2];case 12:return[3,19];case 13:return c=d.sent(),l={error:c},[3,19];case 14:return d.trys.push([14,,17,18]),s&&!s.done&&(h=r.return)?[4,Wn(h.call(r))]:[3,16];case 15:d.sent(),d.label=16;case 16:return[3,18];case 17:if(l)throw l.error;return[7];case 18:return[7];case 19:return[2]}}))}.apply(n,o||[]),a=[];return s={},c("next"),c("throw"),c("return"),s[Symbol.asyncIterator]=function(){return this},s;function c(e){i[e]&&(s[e]=function(t){return new Promise((function(n,o){a.push([e,t,n,o])>1||l(e,t)}))})}function l(e,t){try{(n=i[e](t)).value instanceof Wn?Promise.resolve(n.value.v).then(h,d):u(a[0][2],n)}catch(e){u(a[0][3],e)}var n}function h(e){l("next",e)}function d(e){l("throw",e)}function u(e,t){e(t),a.shift(),a.length&&l(a[0][0],a[0][1])}}(this,arguments)},e.prototype.doDecodeSync=function(){e:for(;;){var e=this.readHeadByte(),t=void 0;if(e>=224)t=e-256;else if(e<192)if(e<128)t=e;else if(e<144){if(0!=(o=e-128)){this.pushMapState(o),this.complete();continue e}t={}}else if(e<160){if(0!=(o=e-144)){this.pushArrayState(o),this.complete();continue e}t=[]}else{var n=e-160;t=this.decodeUtf8String(n,0)}else if(192===e)t=null;else if(194===e)t=!1;else if(195===e)t=!0;else if(202===e)t=this.readF32();else if(203===e)t=this.readF64();else if(204===e)t=this.readU8();else if(205===e)t=this.readU16();else if(206===e)t=this.readU32();else if(207===e)t=this.readU64();else if(208===e)t=this.readI8();else if(209===e)t=this.readI16();else if(210===e)t=this.readI32();else if(211===e)t=this.readI64();else if(217===e)n=this.lookU8(),t=this.decodeUtf8String(n,1);else if(218===e)n=this.lookU16(),t=this.decodeUtf8String(n,2);else if(219===e)n=this.lookU32(),t=this.decodeUtf8String(n,4);else if(220===e){if(0!==(o=this.readU16())){this.pushArrayState(o),this.complete();continue e}t=[]}else if(221===e){if(0!==(o=this.readU32())){this.pushArrayState(o),this.complete();continue e}t=[]}else if(222===e){if(0!==(o=this.readU16())){this.pushMapState(o),this.complete();continue e}t={}}else if(223===e){if(0!==(o=this.readU32())){this.pushMapState(o),this.complete();continue e}t={}}else if(196===e){var o=this.lookU8();t=this.decodeBinary(o,1)}else if(197===e)o=this.lookU16(),t=this.decodeBinary(o,2);else if(198===e)o=this.lookU32(),t=this.decodeBinary(o,4);else if(212===e)t=this.decodeExtension(1,0);else if(213===e)t=this.decodeExtension(2,0);else if(214===e)t=this.decodeExtension(4,0);else if(215===e)t=this.decodeExtension(8,0);else if(216===e)t=this.decodeExtension(16,0);else if(199===e)o=this.lookU8(),t=this.decodeExtension(o,1);else if(200===e)o=this.lookU16(),t=this.decodeExtension(o,2);else{if(201!==e)throw new Un("Unrecognized type byte: ".concat(On(e)));o=this.lookU32(),t=this.decodeExtension(o,4)}this.complete();for(var r=this.stack;r.length>0;){var s=r[r.length-1];if(0===s.type){if(s.array[s.position]=t,s.position++,s.position!==s.size)continue e;r.pop(),t=s.array}else{if(1===s.type){if("string"!=(i=typeof t)&&"number"!==i)throw new Un("The type of key must be string or number but "+typeof t);if("__proto__"===t)throw new Un("The key __proto__ is not allowed");s.key=t,s.type=2;continue e}if(s.map[s.key]=t,s.readCount++,s.readCount!==s.size){s.key=null,s.type=1;continue e}r.pop(),t=s.map}}return t}var i},e.prototype.readHeadByte=function(){return-1===this.headByte&&(this.headByte=this.readU8()),this.headByte},e.prototype.complete=function(){this.headByte=-1},e.prototype.readArraySize=function(){var e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:if(e<160)return e-144;throw new Un("Unrecognized array type byte: ".concat(On(e)))}},e.prototype.pushMapState=function(e){if(e>this.maxMapLength)throw new Un("Max length exceeded: map length (".concat(e,") > maxMapLengthLength (").concat(this.maxMapLength,")"));this.stack.push({type:1,size:e,key:null,readCount:0,map:{}})},e.prototype.pushArrayState=function(e){if(e>this.maxArrayLength)throw new Un("Max length exceeded: array length (".concat(e,") > maxArrayLength (").concat(this.maxArrayLength,")"));this.stack.push({type:0,size:e,array:new Array(e),position:0})},e.prototype.decodeUtf8String=function(e,t){var n;if(e>this.maxStrLength)throw new Un("Max length exceeded: UTF-8 byte length (".concat(e,") > maxStrLength (").concat(this.maxStrLength,")"));if(this.bytes.byteLengthPn?function(e,t,n){var o=e.subarray(t,t+n);return Rn.decode(o)}(this.bytes,r,e):Dn(this.bytes,r,e),this.pos+=t+e,o},e.prototype.stateIsMapKey=function(){return this.stack.length>0&&1===this.stack[this.stack.length-1].type},e.prototype.decodeBinary=function(e,t){if(e>this.maxBinLength)throw new Un("Max length exceeded: bin length (".concat(e,") > maxBinLength (").concat(this.maxBinLength,")"));if(!this.hasRemaining(e+t))throw Kn;var n=this.pos+t,o=this.bytes.subarray(n,n+e);return this.pos+=t+e,o},e.prototype.decodeExtension=function(e,t){if(e>this.maxExtLength)throw new Un("Max length exceeded: ext length (".concat(e,") > maxExtLength (").concat(this.maxExtLength,")"));var n=this.view.getInt8(this.pos+t),o=this.decodeBinary(e,t+1);return this.extensionCodec.decode(o,n,this.context)},e.prototype.lookU8=function(){return this.view.getUint8(this.pos)},e.prototype.lookU16=function(){return this.view.getUint16(this.pos)},e.prototype.lookU32=function(){return this.view.getUint32(this.pos)},e.prototype.readU8=function(){var e=this.view.getUint8(this.pos);return this.pos++,e},e.prototype.readI8=function(){var e=this.view.getInt8(this.pos);return this.pos++,e},e.prototype.readU16=function(){var e=this.view.getUint16(this.pos);return this.pos+=2,e},e.prototype.readI16=function(){var e=this.view.getInt16(this.pos);return this.pos+=2,e},e.prototype.readU32=function(){var e=this.view.getUint32(this.pos);return this.pos+=4,e},e.prototype.readI32=function(){var e=this.view.getInt32(this.pos);return this.pos+=4,e},e.prototype.readU64=function(){var e,t,n=(e=this.view,t=this.pos,4294967296*e.getUint32(t)+e.getUint32(t+4));return this.pos+=8,n},e.prototype.readI64=function(){var e=Sn(this.view,this.pos);return this.pos+=8,e},e.prototype.readF32=function(){var e=this.view.getFloat32(this.pos);return this.pos+=4,e},e.prototype.readF64=function(){var e=this.view.getFloat64(this.pos);return this.pos+=8,e},e}();class Yn{static write(e){let t=e.byteLength||e.length;const n=[];do{let e=127&t;t>>=7,t>0&&(e|=128),n.push(e)}while(t>0);t=e.byteLength||e.length;const o=new Uint8Array(n.length+t);return o.set(n,0),o.set(e,n.length),o.buffer}static parse(e){const t=[],n=new Uint8Array(e),o=[0,7,14,21,28];for(let r=0;r7)throw new Error("Messages bigger than 2GB are not supported.");if(!(n.byteLength>=r+i+a))throw new Error("Incomplete message.");t.push(n.slice?n.slice(r+i,r+i+a):n.subarray(r+i,r+i+a)),r=r+i+a}return t}}const Gn=new Uint8Array([145,Ht.Ping]);class Qn{constructor(e){this.name="messagepack",this.version=2,this.transferFormat=rn.Binary,this._errorResult=1,this._voidResult=2,this._nonVoidResult=3,e=e||{},this._encoder=new $n(e.extensionCodec,e.context,e.maxDepth,e.initialBufferSize,e.sortKeys,e.forceFloat32,e.ignoreUndefined,e.forceIntegerToFloat),this._decoder=new Xn(e.extensionCodec,e.context,e.maxStrLength,e.maxBinLength,e.maxArrayLength,e.maxMapLength,e.maxExtLength)}parseMessages(e,t){if(!(n=e)||"undefined"==typeof ArrayBuffer||!(n instanceof ArrayBuffer||n.constructor&&"ArrayBuffer"===n.constructor.name))throw new Error("Invalid input for MessagePack hub protocol. Expected an ArrayBuffer.");var n;null===t&&(t=yt.instance);const o=Yn.parse(e),r=[];for(const e of o){const n=this._parseMessage(e,t);n&&r.push(n)}return r}writeMessage(e){switch(e.type){case Ht.Invocation:return this._writeInvocation(e);case Ht.StreamInvocation:return this._writeStreamInvocation(e);case Ht.StreamItem:return this._writeStreamItem(e);case Ht.Completion:return this._writeCompletion(e);case Ht.Ping:return Yn.write(Gn);case Ht.CancelInvocation:return this._writeCancelInvocation(e);case Ht.Close:return this._writeClose();case Ht.Ack:return this._writeAck(e);case Ht.Sequence:return this._writeSequence(e);default:throw new Error("Invalid message type.")}}_parseMessage(e,t){if(0===e.length)throw new Error("Invalid payload.");const n=this._decoder.decode(e);if(0===n.length||!(n instanceof Array))throw new Error("Invalid payload.");const o=n[0];switch(o){case Ht.Invocation:return this._createInvocationMessage(this._readHeaders(n),n);case Ht.StreamItem:return this._createStreamItemMessage(this._readHeaders(n),n);case Ht.Completion:return this._createCompletionMessage(this._readHeaders(n),n);case Ht.Ping:return this._createPingMessage(n);case Ht.Close:return this._createCloseMessage(n);case Ht.Ack:return this._createAckMessage(n);case Ht.Sequence:return this._createSequenceMessage(n);default:return t.log(vt.Information,"Unknown message type '"+o+"' ignored."),null}}_createCloseMessage(e){if(e.length<2)throw new Error("Invalid payload for Close message.");return{allowReconnect:e.length>=3?e[2]:void 0,error:e[1],type:Ht.Close}}_createPingMessage(e){if(e.length<1)throw new Error("Invalid payload for Ping message.");return{type:Ht.Ping}}_createInvocationMessage(e,t){if(t.length<5)throw new Error("Invalid payload for Invocation message.");const n=t[2];return n?{arguments:t[4],headers:e,invocationId:n,streamIds:[],target:t[3],type:Ht.Invocation}:{arguments:t[4],headers:e,streamIds:[],target:t[3],type:Ht.Invocation}}_createStreamItemMessage(e,t){if(t.length<4)throw new Error("Invalid payload for StreamItem message.");return{headers:e,invocationId:t[2],item:t[3],type:Ht.StreamItem}}_createCompletionMessage(e,t){if(t.length<4)throw new Error("Invalid payload for Completion message.");const n=t[3];if(n!==this._voidResult&&t.length<5)throw new Error("Invalid payload for Completion message.");let o,r;switch(n){case this._errorResult:o=t[4];break;case this._nonVoidResult:r=t[4]}return{error:o,headers:e,invocationId:t[2],result:r,type:Ht.Completion}}_createAckMessage(e){if(e.length<1)throw new Error("Invalid payload for Ack message.");return{sequenceId:e[1],type:Ht.Ack}}_createSequenceMessage(e){if(e.length<1)throw new Error("Invalid payload for Sequence message.");return{sequenceId:e[1],type:Ht.Sequence}}_writeInvocation(e){let t;return t=e.streamIds?this._encoder.encode([Ht.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments,e.streamIds]):this._encoder.encode([Ht.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments]),Yn.write(t.slice())}_writeStreamInvocation(e){let t;return t=e.streamIds?this._encoder.encode([Ht.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments,e.streamIds]):this._encoder.encode([Ht.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments]),Yn.write(t.slice())}_writeStreamItem(e){const t=this._encoder.encode([Ht.StreamItem,e.headers||{},e.invocationId,e.item]);return Yn.write(t.slice())}_writeCompletion(e){const t=e.error?this._errorResult:void 0!==e.result?this._nonVoidResult:this._voidResult;let n;switch(t){case this._errorResult:n=this._encoder.encode([Ht.Completion,e.headers||{},e.invocationId,t,e.error]);break;case this._voidResult:n=this._encoder.encode([Ht.Completion,e.headers||{},e.invocationId,t]);break;case this._nonVoidResult:n=this._encoder.encode([Ht.Completion,e.headers||{},e.invocationId,t,e.result])}return Yn.write(n.slice())}_writeCancelInvocation(e){const t=this._encoder.encode([Ht.CancelInvocation,e.headers||{},e.invocationId]);return Yn.write(t.slice())}_writeClose(){const e=this._encoder.encode([Ht.Close,null]);return Yn.write(e.slice())}_writeAck(e){const t=this._encoder.encode([Ht.Ack,e.sequenceId]);return Yn.write(t.slice())}_writeSequence(e){const t=this._encoder.encode([Ht.Sequence,e.sequenceId]);return Yn.write(t.slice())}_readHeaders(e){const t=e[1];if("object"!=typeof t)throw new Error("Invalid headers.");return t}}const Zn="function"==typeof TextDecoder?new TextDecoder("utf-8"):null,eo=Zn?Zn.decode.bind(Zn):function(e){let t=0;const n=e.length,o=[],r=[];for(;t65535&&(r-=65536,o.push(r>>>10&1023|55296),r=56320|1023&r),o.push(r)}o.length>1024&&(r.push(String.fromCharCode.apply(null,o)),o.length=0)}return r.push(String.fromCharCode.apply(null,o)),r.join("")},to=Math.pow(2,32),no=Math.pow(2,21)-1;function oo(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function ro(e,t){return e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24>>>0)}function so(e,t){const n=ro(e,t+4);if(n>no)throw new Error(`Cannot read uint64 with high order part ${n}, because the result would exceed Number.MAX_SAFE_INTEGER.`);return n*to+ro(e,t)}class io{constructor(e){this.batchData=e;const t=new ho(e);this.arrayRangeReader=new uo(e),this.arrayBuilderSegmentReader=new po(e),this.diffReader=new ao(e),this.editReader=new co(e,t),this.frameReader=new lo(e,t)}updatedComponents(){return oo(this.batchData,this.batchData.length-20)}referenceFrames(){return oo(this.batchData,this.batchData.length-16)}disposedComponentIds(){return oo(this.batchData,this.batchData.length-12)}disposedEventHandlerIds(){return oo(this.batchData,this.batchData.length-8)}updatedComponentsEntry(e,t){const n=e+4*t;return oo(this.batchData,n)}referenceFramesEntry(e,t){return e+20*t}disposedComponentIdsEntry(e,t){const n=e+4*t;return oo(this.batchData,n)}disposedEventHandlerIdsEntry(e,t){const n=e+8*t;return so(this.batchData,n)}}class ao{constructor(e){this.batchDataUint8=e}componentId(e){return oo(this.batchDataUint8,e)}edits(e){return e+4}editsEntry(e,t){return e+16*t}}class co{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}editType(e){return oo(this.batchDataUint8,e)}siblingIndex(e){return oo(this.batchDataUint8,e+4)}newTreeIndex(e){return oo(this.batchDataUint8,e+8)}moveToSiblingIndex(e){return oo(this.batchDataUint8,e+8)}removedAttributeName(e){const t=oo(this.batchDataUint8,e+12);return this.stringReader.readString(t)}}class lo{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}frameType(e){return oo(this.batchDataUint8,e)}subtreeLength(e){return oo(this.batchDataUint8,e+4)}elementReferenceCaptureId(e){const t=oo(this.batchDataUint8,e+4);return this.stringReader.readString(t)}componentId(e){return oo(this.batchDataUint8,e+8)}elementName(e){const t=oo(this.batchDataUint8,e+8);return this.stringReader.readString(t)}textContent(e){const t=oo(this.batchDataUint8,e+4);return this.stringReader.readString(t)}markupContent(e){const t=oo(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeName(e){const t=oo(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeValue(e){const t=oo(this.batchDataUint8,e+8);return this.stringReader.readString(t)}attributeEventHandlerId(e){return so(this.batchDataUint8,e+12)}}class ho{constructor(e){this.batchDataUint8=e,this.stringTableStartIndex=oo(e,e.length-4)}readString(e){if(-1===e)return null;{const n=oo(this.batchDataUint8,this.stringTableStartIndex+4*e),o=function(e,t){let n=0,o=0;for(let r=0;r<4;r++){const s=e[t+r];if(n|=(127&s)<this.nextBatchId)return this.fatalError?(this.logger.log(ot.Debug,`Received a new batch ${e} but errored out on a previous batch ${this.nextBatchId-1}`),void await n.send("OnRenderCompleted",this.nextBatchId-1,this.fatalError.toString())):void this.logger.log(ot.Debug,`Waiting for batch ${this.nextBatchId}. Batch ${e} not processed.`);try{this.nextBatchId++,this.logger.log(ot.Debug,`Applying batch ${e}.`),function(e,t){const n=fe[e];if(!n)throw new Error(`There is no browser renderer with ID ${e}.`);const o=t.arrayRangeReader,r=t.updatedComponents(),s=o.values(r),i=o.count(r),a=t.referenceFrames(),c=o.values(a),l=t.diffReader;for(let e=0;e{e.onclick=function(e){location.reload(),e.preventDefault()}})),document.querySelectorAll("#blazor-error-ui .dismiss").forEach((e=>{e.onclick=function(e){const t=document.querySelector("#blazor-error-ui");t&&(t.style.display="none"),e.preventDefault()}})))}class vo{constructor(t,n,o,r){this._renderingFailed=!1,this._disposed=!1,this._circuitId=void 0,this._applicationState=n,this._componentManager=t,this._options=o,this._logger=r,this._renderQueue=new fo(this._logger),this._dispatcher=e.attachDispatcher(this)}start(){if(this.isDisposedOrDisposing())throw new Error("Cannot start a disposed circuit.");return this._startPromise||(this._startPromise=this.startCore()),this._startPromise}async startCore(){if(this._connection=await this.startConnection(),this._connection.state!==jt.Connected)return!1;const e=JSON.stringify(this._componentManager.initialComponents.map((e=>{return t=e,{...t,start:void 0,end:void 0};var t})));return this._circuitId=await this._connection.invoke("StartCircuit",Ne.getBaseURI(),Ne.getLocationHref(),e,this._applicationState||""),!!this._circuitId}async startConnection(){var e,t;const n=new Qn;n.name="blazorpack";const o=(new gn).withUrl("_blazor").withHubProtocol(n);this._options.configureSignalR(o);const r=o.build();r.on("JS.AttachComponent",((e,t)=>function(e,t,n,o){let r=fe[e];r||(r=new he(e),fe[e]=r),r.attachRootComponentToLogicalElement(n,t,!1)}(mn.Server,this.resolveElement(t,e),e))),r.on("JS.BeginInvokeJS",this._dispatcher.beginInvokeJSFromDotNet.bind(this._dispatcher)),r.on("JS.EndInvokeDotNet",this._dispatcher.endInvokeDotNetFromJS.bind(this._dispatcher)),r.on("JS.ReceiveByteArray",this._dispatcher.receiveByteArray.bind(this._dispatcher)),r.on("JS.BeginTransmitStream",(e=>{const t=new ReadableStream({start:t=>{r.stream("SendDotNetStreamToJS",e).subscribe({next:e=>t.enqueue(e),complete:()=>t.close(),error:e=>t.error(e)})}});this._dispatcher.supplyDotNetStream(e,t)})),r.on("JS.RenderBatch",(async(e,t)=>{var n,o;this._logger.log(vt.Debug,`Received render batch with id ${e} and ${t.byteLength} bytes.`),await this._renderQueue.processBatch(e,t,this._connection),null===(o=(n=this._componentManager).onAfterRenderBatch)||void 0===o||o.call(n,mn.Server)})),r.on("JS.EndLocationChanging",nt._internal.navigationManager.endLocationChanging),r.onclose((e=>!this._disposed&&!this._renderingFailed&&this._options.reconnectionHandler.onConnectionDown(this._options.reconnectionOptions,e))),r.on("JS.Error",(e=>{this._renderingFailed=!0,this.unhandledError(e),mo()}));try{await r.start()}catch(e){if(this.unhandledError(e),"FailedToNegotiateWithServerError"===e.errorType)throw e;mo(),e.innerErrors&&(e.innerErrors.some((e=>"UnsupportedTransportError"===e.errorType&&e.transport===on.WebSockets))?this._logger.log(vt.Error,"Unable to connect, please ensure you are using an updated browser that supports WebSockets."):e.innerErrors.some((e=>"FailedToStartTransportError"===e.errorType&&e.transport===on.WebSockets))?this._logger.log(vt.Error,"Unable to connect, please ensure WebSockets are available. A VPN or proxy may be blocking the connection."):e.innerErrors.some((e=>"DisabledTransportError"===e.errorType&&e.transport===on.LongPolling))&&this._logger.log(vt.Error,"Unable to initiate a SignalR connection to the server. This might be because the server is not configured to support WebSockets. For additional details, visit https://aka.ms/blazor-server-websockets-error."))}return(null===(t=null===(e=r.connection)||void 0===e?void 0:e.features)||void 0===t?void 0:t.inherentKeepAlive)&&this._logger.log(vt.Warning,"Failed to connect via WebSockets, using the Long Polling fallback transport. This may be due to a VPN or proxy blocking the connection. To troubleshoot this, visit https://aka.ms/blazor-server-using-fallback-long-polling."),r}async disconnect(){var e;await(null===(e=this._connection)||void 0===e?void 0:e.stop())}async reconnect(){if(!this._circuitId)throw new Error("Circuit host not initialized.");return this._connection.state===jt.Connected||(this._connection=await this.startConnection(),!!await this._connection.invoke("ConnectCircuit",this._circuitId)&&(this._options.reconnectionHandler.onConnectionUp(),!0))}beginInvokeDotNetFromJS(e,t,n,o,r){this.throwIfDispatchingWhenDisposed(),this._connection.send("BeginInvokeDotNetFromJS",e?e.toString():null,t,n,o||0,r)}endInvokeJSFromDotNet(e,t,n){this.throwIfDispatchingWhenDisposed(),this._connection.send("EndInvokeJSFromDotNet",e,t,n)}sendByteArray(e,t){this.throwIfDispatchingWhenDisposed(),this._connection.send("ReceiveByteArray",e,t)}throwIfDispatchingWhenDisposed(){if(this._disposed)throw new Error("The circuit associated with this dispatcher is no longer available.")}sendLocationChanged(e,t,n){return this._connection.send("OnLocationChanged",e,t,n)}sendLocationChanging(e,t,n,o){return this._connection.send("OnLocationChanging",e,t,n,o)}sendJsDataStream(e,t,n){return function(e,t,n,o){setTimeout((async()=>{let r=5,s=(new Date).valueOf();try{const i=t instanceof Blob?t.size:t.byteLength;let a=0,c=0;for(;a1)await e.send("ReceiveJSDataChunk",n,c,h,null);else{if(!await e.invoke("ReceiveJSDataChunk",n,c,h,null))break;const t=(new Date).valueOf(),o=t-s;s=t,r=Math.max(1,Math.round(500/Math.max(1,o)))}a+=l,c++}}catch(t){await e.send("ReceiveJSDataChunk",n,-1,null,t.toString())}}),0)}(this._connection,e,t,n)}resolveElement(e,t){const n=function(e){const t=f.get(e);if(t)return f.delete(e),t}(e);if(n)return O(n,!0);const o=Number.parseInt(e);if(!Number.isNaN(o))return function(e){const{start:t,end:n}=e,o=t[$];if(o){if(o!==e)throw new Error("The start component comment was already associated with another component descriptor.");return t}const r=t.parentNode;if(!r)throw new Error(`Comment not connected to the DOM ${t.textContent}`);const s=O(r,!0),i=K(s);t[L]=s,t[$]=e;const a=O(t);if(n){const e=K(a),o=Array.prototype.indexOf.call(i,a)+1;let r=null;for(;r!==n;){const n=i.splice(o,1)[0];if(!n)throw new Error("Could not find the end component comment in the parent logical node list");n[L]=t,e.push(n),r=n}}return a}(this._componentManager.resolveRootComponent(o,t));throw new Error(`Invalid sequence number or identifier '${e}'.`)}getRootComponentManager(){return this._componentManager}unhandledError(e){this._logger.log(vt.Error,e),this.disconnect()}getDisconnectFormData(){const e=new FormData,t=this._circuitId;return e.append("circuitId",t),e}didRenderingFail(){return this._renderingFailed}isDisposedOrDisposing(){return void 0!==this._disposePromise}sendDisconnectBeacon(){if(this._disposed)return;const e=this.getDisconnectFormData();this._disposed=navigator.sendBeacon("_blazor/disconnect",e)}dispose(){return this._disposePromise||(this._disposePromise=this.disposeCore()),this._disposePromise}async disposeCore(){var e;if(!this._startPromise)return void(this._disposed=!0);await this._startPromise,this._disposed=!0,null===(e=this._connection)||void 0===e||e.stop();const t=this.getDisconnectFormData();fetch("_blazor/disconnect",{method:"POST",body:t}),function(e){if(!S.delete(e))throw new Error(`Interop methods are not registered for renderer ${e}`)}(mn.Server)}}const yo={configureSignalR:e=>{},logLevel:ot.Warning,reconnectionOptions:{maxRetries:8,retryIntervalMilliseconds:2e4,dialogId:"components-reconnect-modal"}};class wo{constructor(e,t,n,o){this.maxRetries=t,this.document=n,this.logger=o,this.addedToDom=!1,this.modal=this.document.createElement("div"),this.modal.id=e,this.maxRetries=t,this.modal.style.cssText=["position: fixed","top: 0","right: 0","bottom: 0","left: 0","z-index: 1050","display: none","overflow: hidden","background-color: #fff","opacity: 0.8","text-align: center","font-weight: bold","transition: visibility 0s linear 500ms"].join(";"),this.message=this.document.createElement("h5"),this.message.style.cssText="margin-top: 20px",this.button=this.document.createElement("button"),this.button.style.cssText="margin:5px auto 5px",this.button.textContent="Retry";const r=this.document.createElement("a");r.addEventListener("click",(()=>location.reload())),r.textContent="reload",this.reloadParagraph=this.document.createElement("p"),this.reloadParagraph.textContent="Alternatively, ",this.reloadParagraph.appendChild(r),this.modal.appendChild(this.message),this.modal.appendChild(this.button),this.modal.appendChild(this.reloadParagraph),this.loader=this.getLoader(),this.message.after(this.loader),this.button.addEventListener("click",(async()=>{this.show();try{await nt.reconnect()||this.rejected()}catch(e){this.logger.log(ot.Error,e),this.failed()}}))}show(){this.addedToDom||(this.addedToDom=!0,this.document.body.appendChild(this.modal)),this.modal.style.display="block",this.loader.style.display="inline-block",this.button.style.display="none",this.reloadParagraph.style.display="none",this.message.textContent="Attempting to reconnect to the server...",this.modal.style.visibility="hidden",setTimeout((()=>{this.modal.style.visibility="visible"}),0)}update(e){this.message.textContent=`Attempting to reconnect to the server: ${e} of ${this.maxRetries}`}hide(){this.modal.style.display="none"}failed(){this.button.style.display="block",this.reloadParagraph.style.display="none",this.loader.style.display="none";const e=this.document.createTextNode("Reconnection failed. Try "),t=this.document.createElement("a");t.textContent="reloading",t.setAttribute("href",""),t.addEventListener("click",(()=>location.reload()));const n=this.document.createTextNode(" the page if you're unable to reconnect.");this.message.replaceChildren(e,t,n)}rejected(){this.button.style.display="none",this.reloadParagraph.style.display="none",this.loader.style.display="none";const e=this.document.createTextNode("Could not reconnect to the server. "),t=this.document.createElement("a");t.textContent="Reload",t.setAttribute("href",""),t.addEventListener("click",(()=>location.reload()));const n=this.document.createTextNode(" the page to restore functionality.");this.message.replaceChildren(e,t,n)}getLoader(){const e=this.document.createElement("div");return e.style.cssText=["border: 0.3em solid #f3f3f3","border-top: 0.3em solid #3498db","border-radius: 50%","width: 2em","height: 2em","display: inline-block"].join(";"),e.animate([{transform:"rotate(0deg)"},{transform:"rotate(360deg)"}],{duration:2e3,iterations:1/0}),e}}class _o{constructor(e,t,n){this.dialog=e,this.maxRetries=t,this.document=n,this.document=n;const o=this.document.getElementById(_o.MaxRetriesId);o&&(o.innerText=this.maxRetries.toString())}show(){this.removeClasses(),this.dialog.classList.add(_o.ShowClassName)}update(e){const t=this.document.getElementById(_o.CurrentAttemptId);t&&(t.innerText=e.toString())}hide(){this.removeClasses(),this.dialog.classList.add(_o.HideClassName)}failed(){this.removeClasses(),this.dialog.classList.add(_o.FailedClassName)}rejected(){this.removeClasses(),this.dialog.classList.add(_o.RejectedClassName)}removeClasses(){this.dialog.classList.remove(_o.ShowClassName,_o.HideClassName,_o.FailedClassName,_o.RejectedClassName)}}_o.ShowClassName="components-reconnect-show",_o.HideClassName="components-reconnect-hide",_o.FailedClassName="components-reconnect-failed",_o.RejectedClassName="components-reconnect-rejected",_o.MaxRetriesId="components-reconnect-max-retries",_o.CurrentAttemptId="components-reconnect-current-attempt";class bo{constructor(e,t,n){this._currentReconnectionProcess=null,this._logger=e,this._reconnectionDisplay=t,this._reconnectCallback=n||nt.reconnect}onConnectionDown(e,t){if(!this._reconnectionDisplay){const t=document.getElementById(e.dialogId);this._reconnectionDisplay=t?new _o(t,e.maxRetries,document):new wo(e.dialogId,e.maxRetries,document,this._logger)}this._currentReconnectionProcess||(this._currentReconnectionProcess=new So(e,this._logger,this._reconnectCallback,this._reconnectionDisplay))}onConnectionUp(){this._currentReconnectionProcess&&(this._currentReconnectionProcess.dispose(),this._currentReconnectionProcess=null)}}class So{constructor(e,t,n,o){this.logger=t,this.reconnectCallback=n,this.isDisposed=!1,this.reconnectDisplay=o,this.reconnectDisplay.show(),this.attemptPeriodicReconnection(e)}dispose(){this.isDisposed=!0,this.reconnectDisplay.hide()}async attemptPeriodicReconnection(e){for(let t=0;tSo.MaximumFirstRetryInterval?So.MaximumFirstRetryInterval:e.retryIntervalMilliseconds;if(await this.delay(n),this.isDisposed)break;try{return await this.reconnectCallback()?void 0:void this.reconnectDisplay.rejected()}catch(e){this.logger.log(ot.Error,e)}}this.reconnectDisplay.failed()}delay(e){return new Promise((t=>setTimeout(t,e)))}}So.MaximumFirstRetryInterval=3e3;class Eo{constructor(){this.afterStartedCallbacks=[]}async importInitializersAsync(e,t){await Promise.all(e.map((e=>async function(e,n){const o=function(e){const t=document.baseURI;return t.endsWith("/")?`${t}${e}`:`${t}/${e}`}(n),r=await import(o);if(void 0===r)return;const{beforeStart:s,afterStarted:i}=r;return i&&e.afterStartedCallbacks.push(i),s?s(...t):void 0}(this,e))))}async invokeAfterStartedCallbacks(e){await I,await Promise.all(this.afterStartedCallbacks.map((t=>t(e))))}}let Co,Io,ko,To,Do=!1;async function xo(e){if(Do)throw new Error("Blazor Server has already started.");Do=!0,Co=at(document)||"",To=new st(ko.logLevel),Io=new vo(e,Co,ko,To),To.log(ot.Information,"Starting up Blazor server-side application."),nt.reconnect=async()=>!(Io.didRenderingFail()||!await Io.reconnect()&&(To.log(ot.Information,"Reconnection attempt to the circuit was rejected by the server. This may indicate that the associated state is no longer available on the server."),1)),nt.defaultReconnectionHandler=new bo(To),ko.reconnectionHandler=ko.reconnectionHandler||nt.defaultReconnectionHandler,nt._internal.navigationManager.listenForNavigationEvents(((e,t,n)=>Io.sendLocationChanged(e,t,n)),((e,t,n,o)=>Io.sendLocationChanging(e,t,n,o))),nt._internal.forceCloseConnection=()=>Io.disconnect(),nt._internal.sendJSDataStream=(e,t,n)=>Io.sendJsDataStream(e,t,n);const t=await async function(e){const t=await fetch("_blazor/initializers",{method:"GET",credentials:"include",cache:"no-cache"}),n=await t.json(),o=new Eo;return await o.importInitializersAsync(n,[e]),o}(ko);if(!await Io.start())return void To.log(ot.Error,"Failed to start the circuit.");const n=()=>{Io.sendDisconnectBeacon()};nt.disconnect=n,window.addEventListener("unload",n,{capture:!1,once:!0}),To.log(ot.Information,"Blazor server-side application started."),t.invokeAfterStartedCallbacks(nt)}class Ro{constructor(e){this.initialComponents=e}resolveRootComponent(e,t){return this.initialComponents[e]}}class Po{constructor(){this._eventListeners=new Map}static create(e){const t=new Po;return e.addEventListener=t.addEventListener.bind(t),e.removeEventListener=t.removeEventListener.bind(t),t}addEventListener(e,t){let n=this._eventListeners.get(e);n||(n=new Set,this._eventListeners.set(e,n)),n.add(t)}removeEventListener(e,t){var n;null===(n=this._eventListeners.get(e))||void 0===n||n.delete(t)}dispatchEvent(e,t){const n=this._eventListeners.get(e);if(!n)return;const o={...t,type:e};for(const e of n)e(o)}}let Ao=!1;function No(e){if(Ao)throw new Error("Blazor has already started.");Ao=!0,function(e){if(ko)throw new Error("Circuit options have already been configured.");ko=function(e){const t={...yo,...e};return e&&e.reconnectionOptions&&(t.reconnectionOptions={...yo.reconnectionOptions,...e.reconnectionOptions}),t}(e)}(e),Po.create(nt);const t=function(e){return ct(e,"server").sort(((e,t)=>e.sequence-t.sequence))}(document);return xo(new Ro(t))}nt.start=No,window.DotNet=e,document&&document.currentScript&&"false"!==document.currentScript.getAttribute("autostart")&&No()})()})(); \ No newline at end of file +(()=>{var e={778:()=>{},77:()=>{},203:()=>{},200:()=>{},628:()=>{},321:()=>{}},t={};function n(o){var r=t[o];if(void 0!==r)return r.exports;var s=t[o]={exports:{}};return e[o](s,s.exports,n),s.exports}n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),(()=>{"use strict";var e,t,o;!function(e){const t=[],n="__jsObjectId",o="__dotNetObject",r="__byte[]",s="__dotNetStream",i="__jsStreamReferenceLength";let a,c;class l{constructor(e){this._jsObject=e,this._cachedFunctions=new Map}findFunction(e){const t=this._cachedFunctions.get(e);if(t)return t;let n,o=this._jsObject;if(e.split(".").forEach((t=>{if(!(t in o))throw new Error(`Could not find '${e}' ('${t}' was undefined).`);n=o,o=o[t]})),o instanceof Function)return o=o.bind(n),this._cachedFunctions.set(e,o),o;throw new Error(`The value '${e}' is not a function.`)}getWrappedObject(){return this._jsObject}}const h={0:new l(window)};h[0]._cachedFunctions.set("import",(e=>("string"==typeof e&&e.startsWith("./")&&(e=new URL(e.substr(2),document.baseURI).toString()),import(e))));let d,u=1;function p(e){t.push(e)}function f(e){if(e&&"object"==typeof e){h[u]=new l(e);const t={[n]:u};return u++,t}throw new Error(`Cannot create a JSObjectReference from the value '${e}'.`)}function g(e){let t=-1;if(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),e instanceof Blob)t=e.size;else{if(!(e.buffer instanceof ArrayBuffer))throw new Error("Supplied value is not a typed array or blob.");if(void 0===e.byteLength)throw new Error(`Cannot create a JSStreamReference from the value '${e}' as it doesn't have a byteLength.`);t=e.byteLength}const o={[i]:t};try{const t=f(e);o[n]=t[n]}catch(t){throw new Error(`Cannot create a JSStreamReference from the value '${e}'.`)}return o}function m(e,n){c=e;const o=n?JSON.parse(n,((e,n)=>t.reduce(((t,n)=>n(e,t)),n))):null;return c=void 0,o}function v(){if(void 0===a)throw new Error("No call dispatcher has been set.");if(null===a)throw new Error("There are multiple .NET runtimes present, so a default dispatcher could not be resolved. Use DotNetObject to invoke .NET instance methods.");return a}e.attachDispatcher=function(e){const t=new y(e);return void 0===a?a=t:a&&(a=null),t},e.attachReviver=p,e.invokeMethod=function(e,t,...n){return v().invokeDotNetStaticMethod(e,t,...n)},e.invokeMethodAsync=function(e,t,...n){return v().invokeDotNetStaticMethodAsync(e,t,...n)},e.createJSObjectReference=f,e.createJSStreamReference=g,e.disposeJSObjectReference=function(e){const t=e&&e[n];"number"==typeof t&&b(t)},function(e){e[e.Default=0]="Default",e[e.JSObjectReference=1]="JSObjectReference",e[e.JSStreamReference=2]="JSStreamReference",e[e.JSVoidResult=3]="JSVoidResult"}(d=e.JSCallResultType||(e.JSCallResultType={}));class y{constructor(e){this._dotNetCallDispatcher=e,this._byteArraysToBeRevived=new Map,this._pendingDotNetToJSStreams=new Map,this._pendingAsyncCalls={},this._nextAsyncCallId=1}getDotNetCallDispatcher(){return this._dotNetCallDispatcher}invokeJSFromDotNet(e,t,n,o){const r=m(this,t),s=I(_(e,o)(...r||[]),n);return null==s?null:T(this,s)}beginInvokeJSFromDotNet(e,t,n,o,r){const s=new Promise((e=>{const o=m(this,n);e(_(t,r)(...o||[]))}));e&&s.then((t=>T(this,[e,!0,I(t,o)]))).then((t=>this._dotNetCallDispatcher.endInvokeJSFromDotNet(e,!0,t)),(t=>this._dotNetCallDispatcher.endInvokeJSFromDotNet(e,!1,JSON.stringify([e,!1,w(t)]))))}endInvokeDotNetFromJS(e,t,n){const o=t?m(this,n):new Error(n);this.completePendingCall(parseInt(e,10),t,o)}invokeDotNetStaticMethod(e,t,...n){return this.invokeDotNetMethod(e,t,null,n)}invokeDotNetStaticMethodAsync(e,t,...n){return this.invokeDotNetMethodAsync(e,t,null,n)}invokeDotNetMethod(e,t,n,o){if(this._dotNetCallDispatcher.invokeDotNetFromJS){const r=T(this,o),s=this._dotNetCallDispatcher.invokeDotNetFromJS(e,t,n,r);return s?m(this,s):null}throw new Error("The current dispatcher does not support synchronous calls from JS to .NET. Use invokeDotNetMethodAsync instead.")}invokeDotNetMethodAsync(e,t,n,o){if(e&&n)throw new Error(`For instance method calls, assemblyName should be null. Received '${e}'.`);const r=this._nextAsyncCallId++,s=new Promise(((e,t)=>{this._pendingAsyncCalls[r]={resolve:e,reject:t}}));try{const s=T(this,o);this._dotNetCallDispatcher.beginInvokeDotNetFromJS(r,e,t,n,s)}catch(e){this.completePendingCall(r,!1,e)}return s}receiveByteArray(e,t){this._byteArraysToBeRevived.set(e,t)}processByteArray(e){const t=this._byteArraysToBeRevived.get(e);return t?(this._byteArraysToBeRevived.delete(e),t):null}supplyDotNetStream(e,t){if(this._pendingDotNetToJSStreams.has(e)){const n=this._pendingDotNetToJSStreams.get(e);this._pendingDotNetToJSStreams.delete(e),n.resolve(t)}else{const n=new C;n.resolve(t),this._pendingDotNetToJSStreams.set(e,n)}}getDotNetStreamPromise(e){let t;if(this._pendingDotNetToJSStreams.has(e))t=this._pendingDotNetToJSStreams.get(e).streamPromise,this._pendingDotNetToJSStreams.delete(e);else{const n=new C;this._pendingDotNetToJSStreams.set(e,n),t=n.streamPromise}return t}completePendingCall(e,t,n){if(!this._pendingAsyncCalls.hasOwnProperty(e))throw new Error(`There is no pending async call with ID ${e}.`);const o=this._pendingAsyncCalls[e];delete this._pendingAsyncCalls[e],t?o.resolve(n):o.reject(n)}}function w(e){return e instanceof Error?`${e.message}\n${e.stack}`:e?e.toString():"null"}function _(e,t){const n=h[t];if(n)return n.findFunction(e);throw new Error(`JS object instance with ID ${t} does not exist (has it been disposed?).`)}function b(e){delete h[e]}e.findJSFunction=_,e.disposeJSObjectReferenceById=b;class S{constructor(e,t){this._id=e,this._callDispatcher=t}invokeMethod(e,...t){return this._callDispatcher.invokeDotNetMethod(null,e,this._id,t)}invokeMethodAsync(e,...t){return this._callDispatcher.invokeDotNetMethodAsync(null,e,this._id,t)}dispose(){this._callDispatcher.invokeDotNetMethodAsync(null,"__Dispose",this._id,null).catch((e=>console.error(e)))}serializeAsArg(){return{[o]:this._id}}}e.DotNetObject=S,p((function(e,t){if(t&&"object"==typeof t){if(t.hasOwnProperty(o))return new S(t[o],c);if(t.hasOwnProperty(n)){const e=t[n],o=h[e];if(o)return o.getWrappedObject();throw new Error(`JS object instance with Id '${e}' does not exist. It may have been disposed.`)}if(t.hasOwnProperty(r)){const e=t[r],n=c.processByteArray(e);if(void 0===n)throw new Error(`Byte array index '${e}' does not exist.`);return n}if(t.hasOwnProperty(s)){const e=t[s],n=c.getDotNetStreamPromise(e);return new E(n)}}return t}));class E{constructor(e){this._streamPromise=e}stream(){return this._streamPromise}async arrayBuffer(){return new Response(await this.stream()).arrayBuffer()}}class C{constructor(){this.streamPromise=new Promise(((e,t)=>{this.resolve=e,this.reject=t}))}}function I(e,t){switch(t){case d.Default:return e;case d.JSObjectReference:return f(e);case d.JSStreamReference:return g(e);case d.JSVoidResult:return null;default:throw new Error(`Invalid JS call result type '${t}'.`)}}let k=0;function T(e,t){k=0,c=e;const n=JSON.stringify(t,D);return c=void 0,n}function D(e,t){if(t instanceof S)return t.serializeAsArg();if(t instanceof Uint8Array){c.getDotNetCallDispatcher().sendByteArray(k,t);const e={[r]:k};return k++,e}return t}}(e||(e={})),function(e){e[e.prependFrame=1]="prependFrame",e[e.removeFrame=2]="removeFrame",e[e.setAttribute=3]="setAttribute",e[e.removeAttribute=4]="removeAttribute",e[e.updateText=5]="updateText",e[e.stepIn=6]="stepIn",e[e.stepOut=7]="stepOut",e[e.updateMarkup=8]="updateMarkup",e[e.permutationListEntry=9]="permutationListEntry",e[e.permutationListEnd=10]="permutationListEnd"}(t||(t={})),function(e){e[e.element=1]="element",e[e.text=2]="text",e[e.attribute=3]="attribute",e[e.component=4]="component",e[e.region=5]="region",e[e.elementReferenceCapture=6]="elementReferenceCapture",e[e.markup=8]="markup",e[e.namedEvent=10]="namedEvent"}(o||(o={}));class r{constructor(e,t){this.componentId=e,this.fieldValue=t}static fromEvent(e,t){const n=t.target;if(n instanceof Element){const t=function(e){return e instanceof HTMLInputElement?e.type&&"checkbox"===e.type.toLowerCase()?{value:e.checked}:{value:e.value}:e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement?{value:e.value}:null}(n);if(t)return new r(e,t.value)}return null}}const s=new Map,i=new Map,a=[];function c(e){return s.get(e)}function l(e){const t=s.get(e);return(null==t?void 0:t.browserEventName)||e}function h(e,t){e.forEach((e=>s.set(e,t)))}function d(e){const t=[];for(let n=0;ne.selected)).map((e=>e.value))}}{const e=function(e){return!!e&&"INPUT"===e.tagName&&"checkbox"===e.getAttribute("type")}(t);return{value:e?!!t.checked:t.value}}}}),h(["copy","cut","paste"],{createEventArgs:e=>({type:e.type})}),h(["drag","dragend","dragenter","dragleave","dragover","dragstart","drop"],{createEventArgs:e=>{return{...u(t=e),dataTransfer:t.dataTransfer?{dropEffect:t.dataTransfer.dropEffect,effectAllowed:t.dataTransfer.effectAllowed,files:Array.from(t.dataTransfer.files).map((e=>e.name)),items:Array.from(t.dataTransfer.items).map((e=>({kind:e.kind,type:e.type}))),types:t.dataTransfer.types}:null};var t}}),h(["focus","blur","focusin","focusout"],{createEventArgs:e=>({type:e.type})}),h(["keydown","keyup","keypress"],{createEventArgs:e=>{return{key:(t=e).key,code:t.code,location:t.location,repeat:t.repeat,ctrlKey:t.ctrlKey,shiftKey:t.shiftKey,altKey:t.altKey,metaKey:t.metaKey,type:t.type};var t}}),h(["contextmenu","click","mouseover","mouseout","mousemove","mousedown","mouseup","mouseleave","mouseenter","dblclick"],{createEventArgs:e=>u(e)}),h(["error"],{createEventArgs:e=>{return{message:(t=e).message,filename:t.filename,lineno:t.lineno,colno:t.colno,type:t.type};var t}}),h(["loadstart","timeout","abort","load","loadend","progress"],{createEventArgs:e=>{return{lengthComputable:(t=e).lengthComputable,loaded:t.loaded,total:t.total,type:t.type};var t}}),h(["touchcancel","touchend","touchmove","touchenter","touchleave","touchstart"],{createEventArgs:e=>{return{detail:(t=e).detail,touches:d(t.touches),targetTouches:d(t.targetTouches),changedTouches:d(t.changedTouches),ctrlKey:t.ctrlKey,shiftKey:t.shiftKey,altKey:t.altKey,metaKey:t.metaKey,type:t.type};var t}}),h(["gotpointercapture","lostpointercapture","pointercancel","pointerdown","pointerenter","pointerleave","pointermove","pointerout","pointerover","pointerup"],{createEventArgs:e=>{return{...u(t=e),pointerId:t.pointerId,width:t.width,height:t.height,pressure:t.pressure,tiltX:t.tiltX,tiltY:t.tiltY,pointerType:t.pointerType,isPrimary:t.isPrimary};var t}}),h(["wheel","mousewheel"],{createEventArgs:e=>{return{...u(t=e),deltaX:t.deltaX,deltaY:t.deltaY,deltaZ:t.deltaZ,deltaMode:t.deltaMode};var t}}),h(["cancel","close","toggle"],{createEventArgs:()=>({})});const p=["date","datetime-local","month","time","week"],f=new Map;let g,m,v=0;const y={async add(e,t,n){if(!n)throw new Error("initialParameters must be an object, even if empty.");const o="__bl-dynamic-root:"+(++v).toString();f.set(o,e);const r=await b().invokeMethodAsync("AddRootComponent",t,o),s=new _(r,m[t]);return await s.setParameters(n),s}};class w{invoke(e){return this._callback(e)}setCallback(t){this._selfJSObjectReference||(this._selfJSObjectReference=e.createJSObjectReference(this)),this._callback=t}getJSObjectReference(){return this._selfJSObjectReference}dispose(){this._selfJSObjectReference&&e.disposeJSObjectReference(this._selfJSObjectReference)}}class _{constructor(e,t){this._jsEventCallbackWrappers=new Map,this._componentId=e;for(const e of t)"eventcallback"===e.type&&this._jsEventCallbackWrappers.set(e.name.toLowerCase(),new w)}setParameters(e){const t={},n=Object.entries(e||{}),o=n.length;for(const[e,o]of n){const n=this._jsEventCallbackWrappers.get(e.toLowerCase());n&&o?(n.setCallback(o),t[e]=n.getJSObjectReference()):t[e]=o}return b().invokeMethodAsync("SetRootComponentParameters",this._componentId,o,t)}async dispose(){if(null!==this._componentId){await b().invokeMethodAsync("RemoveRootComponent",this._componentId),this._componentId=null;for(const e of this._jsEventCallbackWrappers.values())e.dispose()}}}function b(){if(!g)throw new Error("Dynamic root components have not been enabled in this application.");return g}const S=new Map,E=[];let C;const I=new Promise((e=>{C=e}));function k(e,t,n){return D(e,t.eventHandlerId,(()=>T(e).invokeMethodAsync("DispatchEventAsync",t,n)))}function T(e){const t=S.get(e);if(!t)throw new Error(`No interop methods are registered for renderer ${e}`);return t}let D=(e,t,n)=>n();const x=M(["abort","blur","cancel","canplay","canplaythrough","change","close","cuechange","durationchange","emptied","ended","error","focus","load","loadeddata","loadedmetadata","loadend","loadstart","mouseenter","mouseleave","pointerenter","pointerleave","pause","play","playing","progress","ratechange","reset","scroll","seeked","seeking","stalled","submit","suspend","timeupdate","toggle","unload","volumechange","waiting","DOMNodeInsertedIntoDocument","DOMNodeRemovedFromDocument"]),R={submit:!0},P=M(["click","dblclick","mousedown","mousemove","mouseup"]);class A{constructor(e){this.browserRendererId=e,this.afterClickCallbacks=[];const t=++A.nextEventDelegatorId;this.eventsCollectionKey=`_blazorEvents_${t}`,this.eventInfoStore=new N(this.onGlobalEvent.bind(this))}setListener(e,t,n,o){const r=this.getEventHandlerInfosForElement(e,!0),s=r.getHandler(t);if(s)this.eventInfoStore.update(s.eventHandlerId,n);else{const s={element:e,eventName:t,eventHandlerId:n,renderingComponentId:o};this.eventInfoStore.add(s),r.setHandler(t,s)}}getHandler(e){return this.eventInfoStore.get(e)}removeListener(e){const t=this.eventInfoStore.remove(e);if(t){const e=t.element,n=this.getEventHandlerInfosForElement(e,!1);n&&n.removeHandler(t.eventName)}}notifyAfterClick(e){this.afterClickCallbacks.push(e),this.eventInfoStore.addGlobalListener("click")}setStopPropagation(e,t,n){this.getEventHandlerInfosForElement(e,!0).stopPropagation(t,n)}setPreventDefault(e,t,n){this.getEventHandlerInfosForElement(e,!0).preventDefault(t,n)}onGlobalEvent(e){if(!(e.target instanceof Element))return;this.dispatchGlobalEventToAllElements(e.type,e);const t=(n=e.type,i.get(n));var n;t&&t.forEach((t=>this.dispatchGlobalEventToAllElements(t,e))),"click"===e.type&&this.afterClickCallbacks.forEach((t=>t(e)))}dispatchGlobalEventToAllElements(e,t){const n=t.composedPath();let o=n.shift(),s=null,i=!1;const a=Object.prototype.hasOwnProperty.call(x,e);let l=!1;for(;o;){const u=o,p=this.getEventHandlerInfosForElement(u,!1);if(p){const n=p.getHandler(e);if(n&&(h=u,d=t.type,!((h instanceof HTMLButtonElement||h instanceof HTMLInputElement||h instanceof HTMLTextAreaElement||h instanceof HTMLSelectElement)&&Object.prototype.hasOwnProperty.call(P,d)&&h.disabled))){if(!i){const n=c(e);s=(null==n?void 0:n.createEventArgs)?n.createEventArgs(t):{},i=!0}Object.prototype.hasOwnProperty.call(R,t.type)&&t.preventDefault(),k(this.browserRendererId,{eventHandlerId:n.eventHandlerId,eventName:e,eventFieldInfo:r.fromEvent(n.renderingComponentId,t)},s)}p.stopPropagation(e)&&(l=!0),p.preventDefault(e)&&t.preventDefault()}o=a||l?void 0:n.shift()}var h,d}getEventHandlerInfosForElement(e,t){return Object.prototype.hasOwnProperty.call(e,this.eventsCollectionKey)?e[this.eventsCollectionKey]:t?e[this.eventsCollectionKey]=new U:null}}A.nextEventDelegatorId=0;class N{constructor(e){this.globalListener=e,this.infosByEventHandlerId={},this.countByEventName={},a.push(this.handleEventNameAliasAdded.bind(this))}add(e){if(this.infosByEventHandlerId[e.eventHandlerId])throw new Error(`Event ${e.eventHandlerId} is already tracked`);this.infosByEventHandlerId[e.eventHandlerId]=e,this.addGlobalListener(e.eventName)}get(e){return this.infosByEventHandlerId[e]}addGlobalListener(e){if(e=l(e),Object.prototype.hasOwnProperty.call(this.countByEventName,e))this.countByEventName[e]++;else{this.countByEventName[e]=1;const t=Object.prototype.hasOwnProperty.call(x,e);document.addEventListener(e,this.globalListener,t)}}update(e,t){if(Object.prototype.hasOwnProperty.call(this.infosByEventHandlerId,t))throw new Error(`Event ${t} is already tracked`);const n=this.infosByEventHandlerId[e];delete this.infosByEventHandlerId[e],n.eventHandlerId=t,this.infosByEventHandlerId[t]=n}remove(e){const t=this.infosByEventHandlerId[e];if(t){delete this.infosByEventHandlerId[e];const n=l(t.eventName);0==--this.countByEventName[n]&&(delete this.countByEventName[n],document.removeEventListener(n,this.globalListener))}return t}handleEventNameAliasAdded(e,t){if(Object.prototype.hasOwnProperty.call(this.countByEventName,e)){const n=this.countByEventName[e];delete this.countByEventName[e],document.removeEventListener(e,this.globalListener),this.addGlobalListener(t),this.countByEventName[t]+=n-1}}}class U{constructor(){this.handlers={},this.preventDefaultFlags=null,this.stopPropagationFlags=null}getHandler(e){return Object.prototype.hasOwnProperty.call(this.handlers,e)?this.handlers[e]:null}setHandler(e,t){this.handlers[e]=t}removeHandler(e){delete this.handlers[e]}preventDefault(e,t){return void 0!==t&&(this.preventDefaultFlags=this.preventDefaultFlags||{},this.preventDefaultFlags[e]=t),!!this.preventDefaultFlags&&this.preventDefaultFlags[e]}stopPropagation(e,t){return void 0!==t&&(this.stopPropagationFlags=this.stopPropagationFlags||{},this.stopPropagationFlags[e]=t),!!this.stopPropagationFlags&&this.stopPropagationFlags[e]}}function M(e){const t={};return e.forEach((e=>{t[e]=!0})),t}const B=Symbol(),L=Symbol(),$=Symbol();function O(e,t){if(B in e)return e;const n=[];if(e.childNodes.length>0){if(!t)throw new Error("New logical elements must start empty, or allowExistingContents must be true");e.childNodes.forEach((t=>{const o=O(t,!0);o[L]=e,n.push(o)}))}return e[B]=n,e}function F(e){const t=K(e);for(;t.length;)W(e,0)}function H(e,t){const n=document.createComment("!");return j(n,e,t),n}function j(e,t,n){const o=e;let r=e;if(B in e){const t=Q(o);if(t!==e){const n=new Range;n.setStartBefore(e),n.setEndAfter(t),r=n.extractContents()}}const s=z(o);if(s){const e=K(s),t=Array.prototype.indexOf.call(e,o);e.splice(t,1),delete o[L]}const i=K(t);if(n0;)W(n,0)}const o=n;o.parentNode.removeChild(o)}function z(e){return e[L]||null}function q(e,t){return K(e)[t]}function J(e){const t=Y(e);return"http://www.w3.org/2000/svg"===t.namespaceURI&&"foreignObject"!==t.tagName}function K(e){return e[B]}function V(e){const t=K(z(e));return t[Array.prototype.indexOf.call(t,e)+1]||null}function X(e,t){const n=K(e);t.forEach((e=>{e.moveRangeStart=n[e.fromSiblingIndex],e.moveRangeEnd=Q(e.moveRangeStart)})),t.forEach((t=>{const o=document.createComment("marker");t.moveToBeforeMarker=o;const r=n[t.toSiblingIndex+1];r?r.parentNode.insertBefore(o,r):G(o,e)})),t.forEach((e=>{const t=e.moveToBeforeMarker,n=t.parentNode,o=e.moveRangeStart,r=e.moveRangeEnd;let s=o;for(;s;){const e=s.nextSibling;if(n.insertBefore(s,t),s===r)break;s=e}n.removeChild(t)})),t.forEach((e=>{n[e.toSiblingIndex]=e.moveRangeStart}))}function Y(e){if(e instanceof Element||e instanceof DocumentFragment)return e;if(e instanceof Comment)return e.parentNode;throw new Error("Not a valid logical element")}function G(e,t){if(t instanceof Element||t instanceof DocumentFragment)t.appendChild(e);else{if(!(t instanceof Comment))throw new Error(`Cannot append node because the parent is not a valid logical element. Parent: ${t}`);{const n=V(t);n?n.parentNode.insertBefore(e,n):G(e,z(t))}}}function Q(e){if(e instanceof Element||e instanceof DocumentFragment)return e;const t=V(e);if(t)return t.previousSibling;{const t=z(e);return t instanceof Element||t instanceof DocumentFragment?t.lastChild:Q(t)}}function Z(e){return`_bl_${e}`}const ee="__internalId";e.attachReviver(((e,t)=>t&&"object"==typeof t&&Object.prototype.hasOwnProperty.call(t,ee)&&"string"==typeof t[ee]?function(e){const t=`[${Z(e)}]`;return document.querySelector(t)}(t[ee]):t));const te="_blazorDeferredValue";function ne(e){return"select-multiple"===e.type}function oe(e,t){e.value=t||""}function re(e,t){e instanceof HTMLSelectElement?ne(e)?function(e,t){t||(t=[]);for(let n=0;n{Ce()&&function(e,t){if(0!==e.button||function(e){return e.ctrlKey||e.shiftKey||e.altKey||e.metaKey}(e))return;if(e.defaultPrevented)return;const n=function(e){const t=!window._blazorDisableComposedPath&&e.composedPath&&e.composedPath();if(t){for(let e=0;edocument.baseURI,getLocationHref:()=>location.href,scrollToElement:Ue};function Ue(e){const t=document.getElementById(e);return!!t&&(t.scrollIntoView(),!0)}function Me(e,t,n=!1){const o=Se(e);!t.forceLoad&&we(o)?We()?Be(o,!1,t.replaceHistoryEntry,t.historyEntryState,n):be(o,t.replaceHistoryEntry):function(e,t){if(location.href===e){const t=e+"?";history.replaceState(null,"",t),location.replace(e)}else t?location.replace(e):location.href=e}(e,t.replaceHistoryEntry)}async function Be(e,t,n,o=void 0,r=!1){if(Oe(),function(e){const t=e.indexOf("#");return t>-1&&location.href.replace(location.hash,"")===e.substring(0,t)}(e))!function(e,t,n){Le(e,t,n);const o=e.indexOf("#");o!==e.length-1&&Ue(e.substring(o+1))}(e,n,o);else{if(!r&&ke&&!await Fe(e,o,t))return;ve=!0,Le(e,n,o),await He(t)}}function Le(e,t,n=void 0){t?history.replaceState({userState:n,_index:Te},"",e):(Te++,history.pushState({userState:n,_index:Te},"",e))}function $e(e){return new Promise((t=>{const n=Pe;Pe=()=>{Pe=n,t()},history.go(e)}))}function Oe(){Ae&&(Ae(!1),Ae=null)}function Fe(e,t,n){return new Promise((o=>{Oe(),Re?(De++,Ae=o,Re(De,e,t,n)):o(!1)}))}async function He(e){var t;xe&&await xe(location.href,null===(t=history.state)||void 0===t?void 0:t.userState,e)}async function je(e){var t,n;Pe&&We()&&await Pe(e),Te=null!==(n=null===(t=history.state)||void 0===t?void 0:t._index)&&void 0!==n?n:0}function We(){return Ce()||!_e()}const ze={focus:function(e,t){if(e instanceof HTMLElement)e.focus({preventScroll:t});else{if(!(e instanceof SVGElement))throw new Error("Unable to focus an invalid element.");if(!e.hasAttribute("tabindex"))throw new Error("Unable to focus an SVG element that does not have a tabindex.");e.focus({preventScroll:t})}},focusBySelector:function(e,t){const n=document.querySelector(e);n&&(n.hasAttribute("tabindex")||(n.tabIndex=-1),n.focus({preventScroll:!0}))}},qe={init:function(e,t,n,o=50){const r=Ke(t);(r||document.documentElement).style.overflowAnchor="none";const s=document.createRange();u(n.parentElement)&&(t.style.display="table-row",n.style.display="table-row");const i=new IntersectionObserver((function(o){o.forEach((o=>{var r;if(!o.isIntersecting)return;s.setStartAfter(t),s.setEndBefore(n);const i=s.getBoundingClientRect().height,a=null===(r=o.rootBounds)||void 0===r?void 0:r.height;o.target===t?e.invokeMethodAsync("OnSpacerBeforeVisible",o.intersectionRect.top-o.boundingClientRect.top,i,a):o.target===n&&n.offsetHeight>0&&e.invokeMethodAsync("OnSpacerAfterVisible",o.boundingClientRect.bottom-o.intersectionRect.bottom,i,a)}))}),{root:r,rootMargin:`${o}px`});i.observe(t),i.observe(n);const a=d(t),c=d(n),{observersByDotNetObjectId:l,id:h}=Ve(e);function d(e){const t={attributes:!0},n=new MutationObserver(((n,o)=>{u(e.parentElement)&&(o.disconnect(),e.style.display="table-row",o.observe(e,t)),i.unobserve(e),i.observe(e)}));return n.observe(e,t),n}function u(e){return null!==e&&(e instanceof HTMLTableElement&&""===e.style.display||"table"===e.style.display||e instanceof HTMLTableSectionElement&&""===e.style.display||"table-row-group"===e.style.display)}l[h]={intersectionObserver:i,mutationObserverBefore:a,mutationObserverAfter:c}},dispose:function(e){const{observersByDotNetObjectId:t,id:n}=Ve(e),o=t[n];o&&(o.intersectionObserver.disconnect(),o.mutationObserverBefore.disconnect(),o.mutationObserverAfter.disconnect(),e.dispose(),delete t[n])}},Je=Symbol();function Ke(e){return e&&e!==document.body&&e!==document.documentElement?"visible"!==getComputedStyle(e).overflowY?e:Ke(e.parentElement):null}function Ve(e){var t;const n=e._callDispatcher,o=e._id;return null!==(t=n[Je])&&void 0!==t||(n[Je]={}),{observersByDotNetObjectId:n[Je],id:o}}const Xe={getAndRemoveExistingTitle:function(){var e;const t=document.head?document.head.getElementsByTagName("title"):[];if(0===t.length)return null;let n=null;for(let o=t.length-1;o>=0;o--){const r=t[o],s=r.previousSibling;s instanceof Comment&&null!==z(s)||(null===n&&(n=r.textContent),null===(e=r.parentNode)||void 0===e||e.removeChild(r))}return n}},Ye={init:function(e,t){t._blazorInputFileNextFileId=0,t.addEventListener("click",(function(){t.value=""})),t.addEventListener("change",(function(){t._blazorFilesById={};const n=Array.prototype.map.call(t.files,(function(e){const n={id:++t._blazorInputFileNextFileId,lastModified:new Date(e.lastModified).toISOString(),name:e.name,size:e.size,contentType:e.type,readPromise:void 0,arrayBuffer:void 0,blob:e};return t._blazorFilesById[n.id]=n,n}));e.invokeMethodAsync("NotifyChange",n)}))},toImageFile:async function(e,t,n,o,r){const s=Ge(e,t),i=await new Promise((function(e){const t=new Image;t.onload=function(){URL.revokeObjectURL(t.src),e(t)},t.onerror=function(){t.onerror=null,URL.revokeObjectURL(t.src)},t.src=URL.createObjectURL(s.blob)})),a=await new Promise((function(e){var t;const s=Math.min(1,o/i.width),a=Math.min(1,r/i.height),c=Math.min(s,a),l=document.createElement("canvas");l.width=Math.round(i.width*c),l.height=Math.round(i.height*c),null===(t=l.getContext("2d"))||void 0===t||t.drawImage(i,0,0,l.width,l.height),l.toBlob(e,n)})),c={id:++e._blazorInputFileNextFileId,lastModified:s.lastModified,name:s.name,size:(null==a?void 0:a.size)||0,contentType:n,blob:a||s.blob};return e._blazorFilesById[c.id]=c,c},readFileData:async function(e,t){return Ge(e,t).blob}};function Ge(e,t){const n=e._blazorFilesById[t];if(!n)throw new Error(`There is no file with ID ${t}. The file list may have changed. See https://aka.ms/aspnet/blazor-input-file-multiple-selections.`);return n}const Qe=new Set,Ze={enableNavigationPrompt:function(e){0===Qe.size&&window.addEventListener("beforeunload",et),Qe.add(e)},disableNavigationPrompt:function(e){Qe.delete(e),0===Qe.size&&window.removeEventListener("beforeunload",et)}};function et(e){e.preventDefault(),e.returnValue=!0}async function tt(e,t,n){return e instanceof Blob?await async function(e,t,n){const o=e.slice(t,t+n),r=await o.arrayBuffer();return new Uint8Array(r)}(e,t,n):function(e,t,n){return new Uint8Array(e.buffer,e.byteOffset+t,n)}(e,t,n)}new Map;const nt={navigateTo:function(e,t,n=!1){Me(e,t instanceof Object?t:{forceLoad:t,replaceHistoryEntry:n})},registerCustomEventType:function(e,t){if(!t)throw new Error("The options parameter is required.");if(s.has(e))throw new Error(`The event '${e}' is already registered.`);if(t.browserEventName){const n=i.get(t.browserEventName);n?n.push(e):i.set(t.browserEventName,[e]),a.forEach((n=>n(e,t.browserEventName)))}s.set(e,t)},rootComponents:y,runtime:{},_internal:{navigationManager:Ne,domWrapper:ze,Virtualize:qe,PageTitle:Xe,InputFile:Ye,NavigationLock:Ze,getJSDataStreamChunk:tt,attachWebRendererInterop:function(t,n,o,r){if(S.has(t))throw new Error(`Interop methods are already registered for renderer ${t}`);S.set(t,n),Object.keys(o).length>0&&function(t,n,o){if(g)throw new Error("Dynamic root components have already been enabled.");g=t,m=n;for(const[t,r]of Object.entries(o)){const o=e.findJSFunction(t,0);for(const e of r)o(e,n[e])}}(T(t),o,r),C(),function(e){for(const t of E)t(e)}(t)}}};var ot;window.Blazor=nt,function(e){e[e.Trace=0]="Trace",e[e.Debug=1]="Debug",e[e.Information=2]="Information",e[e.Warning=3]="Warning",e[e.Error=4]="Error",e[e.Critical=5]="Critical",e[e.None=6]="None"}(ot||(ot={}));class rt{log(e,t){}}rt.instance=new rt;class st{constructor(e){this.minLevel=e}log(e,t){if(e>=this.minLevel){const n=`[${(new Date).toISOString()}] ${ot[e]}: ${t}`;switch(e){case ot.Critical:case ot.Error:console.error(n);break;case ot.Warning:console.warn(n);break;case ot.Information:console.info(n);break;default:console.log(n)}}}}const it=/^\s*Blazor-Server-Component-State:(?[a-zA-Z0-9+/=]+)$/;function at(e,t){var n;if(e.nodeType===Node.COMMENT_NODE){const o=e.textContent||"",r=t.exec(o),s=r&&r.groups&&r.groups.state;return s&&(null===(n=e.parentNode)||void 0===n||n.removeChild(e)),s}if(!e.hasChildNodes())return;const o=e.childNodes;for(let e=0;e.*)$/);function ht(e,t){const n=e.currentElement;var o,r,s;if(n&&n.nodeType===Node.COMMENT_NODE&&n.textContent){const i=lt.exec(n.textContent),a=i&&i.groups&&i.groups.descriptor;if(!a)return;!function(e){if(e.parentNode instanceof Document)throw new Error("Root components cannot be marked as interactive. The element must be rendered statically so that scripts are not evaluated multiple times.")}(n);try{const i=function(e){const t=JSON.parse(e),{type:n}=t;if("server"!==n&&"webassembly"!==n&&"auto"!==n)throw new Error(`Invalid component type '${n}'.`);return t}(a),c=function(e,t,n){const{prerenderId:o}=e;if(o){for(;n.next()&&n.currentElement;){const e=n.currentElement;if(e.nodeType!==Node.COMMENT_NODE)continue;if(!e.textContent)continue;const t=lt.exec(e.textContent),r=t&&t[1];if(r)return ft(r,o),e}throw new Error(`Could not find an end component comment for '${t}'.`)}}(i,n,e);if(t!==i.type)return;switch(i.type){case"webassembly":return r=n,s=c,pt(o=i),{...o,uniqueId:dt++,start:r,end:s};case"server":return function(e,t,n){return ut(e),{...e,uniqueId:dt++,start:t,end:n}}(i,n,c);case"auto":return function(e,t,n){return ut(e),pt(e),{...e,uniqueId:dt++,start:t,end:n}}(i,n,c)}}catch(e){throw new Error(`Found malformed component comment at ${n.textContent}`)}}}let dt=0;function ut(e){const{descriptor:t,sequence:n}=e;if(!t)throw new Error("descriptor must be defined when using a descriptor.");if(void 0===n)throw new Error("sequence must be defined when using a descriptor.");if(!Number.isInteger(n))throw new Error(`Error parsing the sequence '${n}' for component '${JSON.stringify(e)}'`)}function pt(e){const{assembly:t,typeName:n}=e;if(!t)throw new Error("assembly must be defined when using a descriptor.");if(!n)throw new Error("typeName must be defined when using a descriptor.");e.parameterDefinitions=e.parameterDefinitions&&atob(e.parameterDefinitions),e.parameterValues=e.parameterValues&&atob(e.parameterValues)}function ft(e,t){const n=JSON.parse(e);if(1!==Object.keys(n).length)throw new Error(`Invalid end of component comment: '${e}'`);const o=n.prerenderId;if(!o)throw new Error(`End of component comment must have a value for the prerendered property: '${e}'`);if(o!==t)throw new Error(`End of component comment prerendered property must match the start comment prerender id: '${t}', '${o}'`)}class gt{constructor(e){this.childNodes=e,this.currentIndex=-1,this.length=e.length}next(){return this.currentIndex++,this.currentIndex{n+=`0x${e<16?"0":""}${e.toString(16)} `})),n.substr(0,n.length-1)}(e)}'`)):"string"==typeof e&&(n=`String data of length ${e.length}`,t&&(n+=`. Content: '${e}'`)),n}function Et(e){return e&&"undefined"!=typeof ArrayBuffer&&(e instanceof ArrayBuffer||e.constructor&&"ArrayBuffer"===e.constructor.name)}async function Ct(e,t,n,o,r,s){const i={},[a,c]=Tt();i[a]=c,e.log(vt.Trace,`(${t} transport) sending data. ${St(r,s.logMessageContent)}.`);const l=Et(r)?"arraybuffer":"text",h=await n.post(o,{content:r,headers:{...i,...s.headers},responseType:l,timeout:s.timeout,withCredentials:s.withCredentials});e.log(vt.Trace,`(${t} transport) request complete. Response status: ${h.statusCode}.`)}class It{constructor(e,t){this._subject=e,this._observer=t}dispose(){const e=this._subject.observers.indexOf(this._observer);e>-1&&this._subject.observers.splice(e,1),0===this._subject.observers.length&&this._subject.cancelCallback&&this._subject.cancelCallback().catch((e=>{}))}}class kt{constructor(e){this._minLevel=e,this.out=console}log(e,t){if(e>=this._minLevel){const n=`[${(new Date).toISOString()}] ${vt[e]}: ${t}`;switch(e){case vt.Critical:case vt.Error:this.out.error(n);break;case vt.Warning:this.out.warn(n);break;case vt.Information:this.out.info(n);break;default:this.out.log(n)}}}}function Tt(){let e="X-SignalR-User-Agent";return bt.isNode&&(e="User-Agent"),[e,Dt(wt,xt(),bt.isNode?"NodeJS":"Browser",Rt())]}function Dt(e,t,n,o){let r="Microsoft SignalR/";const s=e.split(".");return r+=`${s[0]}.${s[1]}`,r+=` (${e}; `,r+=t&&""!==t?`${t}; `:"Unknown OS; ",r+=`${n}`,r+=o?`; ${o}`:"; Unknown Runtime Version",r+=")",r}function xt(){if(!bt.isNode)return"";switch(process.platform){case"win32":return"Windows NT";case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}}function Rt(){if(bt.isNode)return process.versions.node}function Pt(e){return e.stack?e.stack:e.message?e.message:`${e}`}class At{writeHandshakeRequest(e){return mt.write(JSON.stringify(e))}parseHandshakeResponse(e){let t,n;if(Et(e)){const o=new Uint8Array(e),r=o.indexOf(mt.RecordSeparatorCode);if(-1===r)throw new Error("Message is incomplete.");const s=r+1;t=String.fromCharCode.apply(null,Array.prototype.slice.call(o.slice(0,s))),n=o.byteLength>s?o.slice(s).buffer:null}else{const o=e,r=o.indexOf(mt.RecordSeparator);if(-1===r)throw new Error("Message is incomplete.");const s=r+1;t=o.substring(0,s),n=o.length>s?o.substring(s):null}const o=mt.parse(t),r=JSON.parse(o[0]);if(r.type)throw new Error("Expected a handshake response from the server.");return[n,r]}}class Nt extends Error{constructor(e,t){const n=new.target.prototype;super(`${e}: Status code '${t}'`),this.statusCode=t,this.__proto__=n}}class Ut extends Error{constructor(e="A timeout occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class Mt extends Error{constructor(e="An abort occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class Bt extends Error{constructor(e,t){const n=new.target.prototype;super(e),this.transport=t,this.errorType="UnsupportedTransportError",this.__proto__=n}}class Lt extends Error{constructor(e,t){const n=new.target.prototype;super(e),this.transport=t,this.errorType="DisabledTransportError",this.__proto__=n}}class $t extends Error{constructor(e,t){const n=new.target.prototype;super(e),this.transport=t,this.errorType="FailedToStartTransportError",this.__proto__=n}}class Ot extends Error{constructor(e){const t=new.target.prototype;super(e),this.errorType="FailedToNegotiateWithServerError",this.__proto__=t}}class Ft extends Error{constructor(e,t){const n=new.target.prototype;super(e),this.innerErrors=t,this.__proto__=n}}var Ht,jt;!function(e){e[e.Invocation=1]="Invocation",e[e.StreamItem=2]="StreamItem",e[e.Completion=3]="Completion",e[e.StreamInvocation=4]="StreamInvocation",e[e.CancelInvocation=5]="CancelInvocation",e[e.Ping=6]="Ping",e[e.Close=7]="Close",e[e.Ack=8]="Ack",e[e.Sequence=9]="Sequence"}(Ht||(Ht={}));class Wt{constructor(){this.observers=[]}next(e){for(const t of this.observers)t.next(e)}error(e){for(const t of this.observers)t.error&&t.error(e)}complete(){for(const e of this.observers)e.complete&&e.complete()}subscribe(e){return this.observers.push(e),new It(this,e)}}class zt{constructor(e,t,n){this._bufferSize=1e5,this._messages=[],this._totalMessageCount=0,this._waitForSequenceMessage=!1,this._nextReceivingSequenceId=1,this._latestReceivedSequenceId=0,this._bufferedByteCount=0,this._reconnectInProgress=!1,this._protocol=e,this._connection=t,this._bufferSize=n}async _send(e){const t=this._protocol.writeMessage(e);let n=Promise.resolve();if(this._isInvocationMessage(e)){this._totalMessageCount++;let e=()=>{},o=()=>{};Et(t)?this._bufferedByteCount+=t.byteLength:this._bufferedByteCount+=t.length,this._bufferedByteCount>=this._bufferSize&&(n=new Promise(((t,n)=>{e=t,o=n}))),this._messages.push(new qt(t,this._totalMessageCount,e,o))}try{this._reconnectInProgress||await this._connection.send(t)}catch{this._disconnected()}await n}_ack(e){let t=-1;for(let n=0;nthis._nextReceivingSequenceId?this._connection.stop(new Error("Sequence ID greater than amount of messages we've received.")):this._nextReceivingSequenceId=e.sequenceId}_disconnected(){this._reconnectInProgress=!0,this._waitForSequenceMessage=!0}async _resend(){const e=0!==this._messages.length?this._messages[0]._id:this._totalMessageCount+1;await this._connection.send(this._protocol.writeMessage({type:Ht.Sequence,sequenceId:e}));const t=this._messages;for(const e of t)await this._connection.send(e._message);this._reconnectInProgress=!1}_dispose(e){null!=e||(e=new Error("Unable to reconnect to server."));for(const t of this._messages)t._rejector(e)}_isInvocationMessage(e){switch(e.type){case Ht.Invocation:case Ht.StreamItem:case Ht.Completion:case Ht.StreamInvocation:case Ht.CancelInvocation:return!0;case Ht.Close:case Ht.Sequence:case Ht.Ping:case Ht.Ack:return!1}}_ackTimer(){void 0===this._ackTimerHandle&&(this._ackTimerHandle=setTimeout((async()=>{try{this._reconnectInProgress||await this._connection.send(this._protocol.writeMessage({type:Ht.Ack,sequenceId:this._latestReceivedSequenceId}))}catch{}clearTimeout(this._ackTimerHandle),this._ackTimerHandle=void 0}),1e3))}}class qt{constructor(e,t,n,o){this._message=e,this._id=t,this._resolver=n,this._rejector=o}}!function(e){e.Disconnected="Disconnected",e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Reconnecting="Reconnecting"}(jt||(jt={}));class Jt{static create(e,t,n,o,r,s,i){return new Jt(e,t,n,o,r,s,i)}constructor(e,t,n,o,r,s,i){this._nextKeepAlive=0,this._freezeEventListener=()=>{this._logger.log(vt.Warning,"The page is being frozen, this will likely lead to the connection being closed and messages being lost. For more information see the docs at https://learn.microsoft.com/aspnet/core/signalr/javascript-client#bsleep")},_t.isRequired(e,"connection"),_t.isRequired(t,"logger"),_t.isRequired(n,"protocol"),this.serverTimeoutInMilliseconds=null!=r?r:3e4,this.keepAliveIntervalInMilliseconds=null!=s?s:15e3,this._statefulReconnectBufferSize=null!=i?i:1e5,this._logger=t,this._protocol=n,this.connection=e,this._reconnectPolicy=o,this._handshakeProtocol=new At,this.connection.onreceive=e=>this._processIncomingData(e),this.connection.onclose=e=>this._connectionClosed(e),this._callbacks={},this._methods={},this._closedCallbacks=[],this._reconnectingCallbacks=[],this._reconnectedCallbacks=[],this._invocationId=0,this._receivedHandshakeResponse=!1,this._connectionState=jt.Disconnected,this._connectionStarted=!1,this._cachedPingMessage=this._protocol.writeMessage({type:Ht.Ping})}get state(){return this._connectionState}get connectionId(){return this.connection&&this.connection.connectionId||null}get baseUrl(){return this.connection.baseUrl||""}set baseUrl(e){if(this._connectionState!==jt.Disconnected&&this._connectionState!==jt.Reconnecting)throw new Error("The HubConnection must be in the Disconnected or Reconnecting state to change the url.");if(!e)throw new Error("The HubConnection url must be a valid url.");this.connection.baseUrl=e}start(){return this._startPromise=this._startWithStateTransitions(),this._startPromise}async _startWithStateTransitions(){if(this._connectionState!==jt.Disconnected)return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."));this._connectionState=jt.Connecting,this._logger.log(vt.Debug,"Starting HubConnection.");try{await this._startInternal(),bt.isBrowser&&window.document.addEventListener("freeze",this._freezeEventListener),this._connectionState=jt.Connected,this._connectionStarted=!0,this._logger.log(vt.Debug,"HubConnection connected successfully.")}catch(e){return this._connectionState=jt.Disconnected,this._logger.log(vt.Debug,`HubConnection failed to start successfully because of error '${e}'.`),Promise.reject(e)}}async _startInternal(){this._stopDuringStartError=void 0,this._receivedHandshakeResponse=!1;const e=new Promise(((e,t)=>{this._handshakeResolver=e,this._handshakeRejecter=t}));await this.connection.start(this._protocol.transferFormat);try{let t=this._protocol.version;this.connection.features.reconnect||(t=1);const n={protocol:this._protocol.name,version:t};if(this._logger.log(vt.Debug,"Sending handshake request."),await this._sendMessage(this._handshakeProtocol.writeHandshakeRequest(n)),this._logger.log(vt.Information,`Using HubProtocol '${this._protocol.name}'.`),this._cleanupTimeout(),this._resetTimeoutPeriod(),this._resetKeepAliveInterval(),await e,this._stopDuringStartError)throw this._stopDuringStartError;!!this.connection.features.reconnect&&(this._messageBuffer=new zt(this._protocol,this.connection,this._statefulReconnectBufferSize),this.connection.features.disconnected=this._messageBuffer._disconnected.bind(this._messageBuffer),this.connection.features.resend=()=>{if(this._messageBuffer)return this._messageBuffer._resend()}),this.connection.features.inherentKeepAlive||await this._sendMessage(this._cachedPingMessage)}catch(e){throw this._logger.log(vt.Debug,`Hub handshake failed with error '${e}' during start(). Stopping HubConnection.`),this._cleanupTimeout(),this._cleanupPingTimer(),await this.connection.stop(e),e}}async stop(){const e=this._startPromise;this.connection.features.reconnect=!1,this._stopPromise=this._stopInternal(),await this._stopPromise;try{await e}catch(e){}}_stopInternal(e){if(this._connectionState===jt.Disconnected)return this._logger.log(vt.Debug,`Call to HubConnection.stop(${e}) ignored because it is already in the disconnected state.`),Promise.resolve();if(this._connectionState===jt.Disconnecting)return this._logger.log(vt.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnecting state.`),this._stopPromise;const t=this._connectionState;return this._connectionState=jt.Disconnecting,this._logger.log(vt.Debug,"Stopping HubConnection."),this._reconnectDelayHandle?(this._logger.log(vt.Debug,"Connection stopped during reconnect delay. Done reconnecting."),clearTimeout(this._reconnectDelayHandle),this._reconnectDelayHandle=void 0,this._completeClose(),Promise.resolve()):(t===jt.Connected&&this._sendCloseMessage(),this._cleanupTimeout(),this._cleanupPingTimer(),this._stopDuringStartError=e||new Mt("The connection was stopped before the hub handshake could complete."),this.connection.stop(e))}async _sendCloseMessage(){try{await this._sendWithProtocol(this._createCloseMessage())}catch{}}stream(e,...t){const[n,o]=this._replaceStreamingParams(t),r=this._createStreamInvocation(e,t,o);let s;const i=new Wt;return i.cancelCallback=()=>{const e=this._createCancelInvocation(r.invocationId);return delete this._callbacks[r.invocationId],s.then((()=>this._sendWithProtocol(e)))},this._callbacks[r.invocationId]=(e,t)=>{t?i.error(t):e&&(e.type===Ht.Completion?e.error?i.error(new Error(e.error)):i.complete():i.next(e.item))},s=this._sendWithProtocol(r).catch((e=>{i.error(e),delete this._callbacks[r.invocationId]})),this._launchStreams(n,s),i}_sendMessage(e){return this._resetKeepAliveInterval(),this.connection.send(e)}_sendWithProtocol(e){return this._messageBuffer?this._messageBuffer._send(e):this._sendMessage(this._protocol.writeMessage(e))}send(e,...t){const[n,o]=this._replaceStreamingParams(t),r=this._sendWithProtocol(this._createInvocation(e,t,!0,o));return this._launchStreams(n,r),r}invoke(e,...t){const[n,o]=this._replaceStreamingParams(t),r=this._createInvocation(e,t,!1,o);return new Promise(((e,t)=>{this._callbacks[r.invocationId]=(n,o)=>{o?t(o):n&&(n.type===Ht.Completion?n.error?t(new Error(n.error)):e(n.result):t(new Error(`Unexpected message type: ${n.type}`)))};const o=this._sendWithProtocol(r).catch((e=>{t(e),delete this._callbacks[r.invocationId]}));this._launchStreams(n,o)}))}on(e,t){e&&t&&(e=e.toLowerCase(),this._methods[e]||(this._methods[e]=[]),-1===this._methods[e].indexOf(t)&&this._methods[e].push(t))}off(e,t){if(!e)return;e=e.toLowerCase();const n=this._methods[e];if(n)if(t){const o=n.indexOf(t);-1!==o&&(n.splice(o,1),0===n.length&&delete this._methods[e])}else delete this._methods[e]}onclose(e){e&&this._closedCallbacks.push(e)}onreconnecting(e){e&&this._reconnectingCallbacks.push(e)}onreconnected(e){e&&this._reconnectedCallbacks.push(e)}_processIncomingData(e){if(this._cleanupTimeout(),this._receivedHandshakeResponse||(e=this._processHandshakeResponse(e),this._receivedHandshakeResponse=!0),e){const t=this._protocol.parseMessages(e,this._logger);for(const e of t)if(!this._messageBuffer||this._messageBuffer._shouldProcessMessage(e))switch(e.type){case Ht.Invocation:this._invokeClientMethod(e);break;case Ht.StreamItem:case Ht.Completion:{const t=this._callbacks[e.invocationId];if(t){e.type===Ht.Completion&&delete this._callbacks[e.invocationId];try{t(e)}catch(e){this._logger.log(vt.Error,`Stream callback threw error: ${Pt(e)}`)}}break}case Ht.Ping:break;case Ht.Close:{this._logger.log(vt.Information,"Close message received from server.");const t=e.error?new Error("Server returned an error on close: "+e.error):void 0;!0===e.allowReconnect?this.connection.stop(t):this._stopPromise=this._stopInternal(t);break}case Ht.Ack:this._messageBuffer&&this._messageBuffer._ack(e);break;case Ht.Sequence:this._messageBuffer&&this._messageBuffer._resetSequence(e);break;default:this._logger.log(vt.Warning,`Invalid message type: ${e.type}.`)}}this._resetTimeoutPeriod()}_processHandshakeResponse(e){let t,n;try{[n,t]=this._handshakeProtocol.parseHandshakeResponse(e)}catch(e){const t="Error parsing handshake response: "+e;this._logger.log(vt.Error,t);const n=new Error(t);throw this._handshakeRejecter(n),n}if(t.error){const e="Server returned handshake error: "+t.error;this._logger.log(vt.Error,e);const n=new Error(e);throw this._handshakeRejecter(n),n}return this._logger.log(vt.Debug,"Server handshake complete."),this._handshakeResolver(),n}_resetKeepAliveInterval(){this.connection.features.inherentKeepAlive||(this._nextKeepAlive=(new Date).getTime()+this.keepAliveIntervalInMilliseconds,this._cleanupPingTimer())}_resetTimeoutPeriod(){if(!(this.connection.features&&this.connection.features.inherentKeepAlive||(this._timeoutHandle=setTimeout((()=>this.serverTimeout()),this.serverTimeoutInMilliseconds),void 0!==this._pingServerHandle))){let e=this._nextKeepAlive-(new Date).getTime();e<0&&(e=0),this._pingServerHandle=setTimeout((async()=>{if(this._connectionState===jt.Connected)try{await this._sendMessage(this._cachedPingMessage)}catch{this._cleanupPingTimer()}}),e)}}serverTimeout(){this.connection.stop(new Error("Server timeout elapsed without receiving a message from the server."))}async _invokeClientMethod(e){const t=e.target.toLowerCase(),n=this._methods[t];if(!n)return this._logger.log(vt.Warning,`No client method with the name '${t}' found.`),void(e.invocationId&&(this._logger.log(vt.Warning,`No result given for '${t}' method and invocation ID '${e.invocationId}'.`),await this._sendWithProtocol(this._createCompletionMessage(e.invocationId,"Client didn't provide a result.",null))));const o=n.slice(),r=!!e.invocationId;let s,i,a;for(const n of o)try{const o=s;s=await n.apply(this,e.arguments),r&&s&&o&&(this._logger.log(vt.Error,`Multiple results provided for '${t}'. Sending error to server.`),a=this._createCompletionMessage(e.invocationId,"Client provided multiple results.",null)),i=void 0}catch(e){i=e,this._logger.log(vt.Error,`A callback for the method '${t}' threw error '${e}'.`)}a?await this._sendWithProtocol(a):r?(i?a=this._createCompletionMessage(e.invocationId,`${i}`,null):void 0!==s?a=this._createCompletionMessage(e.invocationId,null,s):(this._logger.log(vt.Warning,`No result given for '${t}' method and invocation ID '${e.invocationId}'.`),a=this._createCompletionMessage(e.invocationId,"Client didn't provide a result.",null)),await this._sendWithProtocol(a)):s&&this._logger.log(vt.Error,`Result given for '${t}' method but server is not expecting a result.`)}_connectionClosed(e){this._logger.log(vt.Debug,`HubConnection.connectionClosed(${e}) called while in state ${this._connectionState}.`),this._stopDuringStartError=this._stopDuringStartError||e||new Mt("The underlying connection was closed before the hub handshake could complete."),this._handshakeResolver&&this._handshakeResolver(),this._cancelCallbacksWithError(e||new Error("Invocation canceled due to the underlying connection being closed.")),this._cleanupTimeout(),this._cleanupPingTimer(),this._connectionState===jt.Disconnecting?this._completeClose(e):this._connectionState===jt.Connected&&this._reconnectPolicy?this._reconnect(e):this._connectionState===jt.Connected&&this._completeClose(e)}_completeClose(e){if(this._connectionStarted){this._connectionState=jt.Disconnected,this._connectionStarted=!1,this._messageBuffer&&(this._messageBuffer._dispose(null!=e?e:new Error("Connection closed.")),this._messageBuffer=void 0),bt.isBrowser&&window.document.removeEventListener("freeze",this._freezeEventListener);try{this._closedCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(vt.Error,`An onclose callback called with error '${e}' threw error '${t}'.`)}}}async _reconnect(e){const t=Date.now();let n=0,o=void 0!==e?e:new Error("Attempting to reconnect due to a unknown error."),r=this._getNextRetryDelay(n++,0,o);if(null===r)return this._logger.log(vt.Debug,"Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt."),void this._completeClose(e);if(this._connectionState=jt.Reconnecting,e?this._logger.log(vt.Information,`Connection reconnecting because of error '${e}'.`):this._logger.log(vt.Information,"Connection reconnecting."),0!==this._reconnectingCallbacks.length){try{this._reconnectingCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(vt.Error,`An onreconnecting callback called with error '${e}' threw error '${t}'.`)}if(this._connectionState!==jt.Reconnecting)return void this._logger.log(vt.Debug,"Connection left the reconnecting state in onreconnecting callback. Done reconnecting.")}for(;null!==r;){if(this._logger.log(vt.Information,`Reconnect attempt number ${n} will start in ${r} ms.`),await new Promise((e=>{this._reconnectDelayHandle=setTimeout(e,r)})),this._reconnectDelayHandle=void 0,this._connectionState!==jt.Reconnecting)return void this._logger.log(vt.Debug,"Connection left the reconnecting state during reconnect delay. Done reconnecting.");try{if(await this._startInternal(),this._connectionState=jt.Connected,this._logger.log(vt.Information,"HubConnection reconnected successfully."),0!==this._reconnectedCallbacks.length)try{this._reconnectedCallbacks.forEach((e=>e.apply(this,[this.connection.connectionId])))}catch(e){this._logger.log(vt.Error,`An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${e}'.`)}return}catch(e){if(this._logger.log(vt.Information,`Reconnect attempt failed because of error '${e}'.`),this._connectionState!==jt.Reconnecting)return this._logger.log(vt.Debug,`Connection moved to the '${this._connectionState}' from the reconnecting state during reconnect attempt. Done reconnecting.`),void(this._connectionState===jt.Disconnecting&&this._completeClose());o=e instanceof Error?e:new Error(e.toString()),r=this._getNextRetryDelay(n++,Date.now()-t,o)}}this._logger.log(vt.Information,`Reconnect retries have been exhausted after ${Date.now()-t} ms and ${n} failed attempts. Connection disconnecting.`),this._completeClose()}_getNextRetryDelay(e,t,n){try{return this._reconnectPolicy.nextRetryDelayInMilliseconds({elapsedMilliseconds:t,previousRetryCount:e,retryReason:n})}catch(n){return this._logger.log(vt.Error,`IRetryPolicy.nextRetryDelayInMilliseconds(${e}, ${t}) threw error '${n}'.`),null}}_cancelCallbacksWithError(e){const t=this._callbacks;this._callbacks={},Object.keys(t).forEach((n=>{const o=t[n];try{o(null,e)}catch(t){this._logger.log(vt.Error,`Stream 'error' callback called with '${e}' threw error: ${Pt(t)}`)}}))}_cleanupPingTimer(){this._pingServerHandle&&(clearTimeout(this._pingServerHandle),this._pingServerHandle=void 0)}_cleanupTimeout(){this._timeoutHandle&&clearTimeout(this._timeoutHandle)}_createInvocation(e,t,n,o){if(n)return 0!==o.length?{arguments:t,streamIds:o,target:e,type:Ht.Invocation}:{arguments:t,target:e,type:Ht.Invocation};{const n=this._invocationId;return this._invocationId++,0!==o.length?{arguments:t,invocationId:n.toString(),streamIds:o,target:e,type:Ht.Invocation}:{arguments:t,invocationId:n.toString(),target:e,type:Ht.Invocation}}}_launchStreams(e,t){if(0!==e.length){t||(t=Promise.resolve());for(const n in e)e[n].subscribe({complete:()=>{t=t.then((()=>this._sendWithProtocol(this._createCompletionMessage(n))))},error:e=>{let o;o=e instanceof Error?e.message:e&&e.toString?e.toString():"Unknown error",t=t.then((()=>this._sendWithProtocol(this._createCompletionMessage(n,o))))},next:e=>{t=t.then((()=>this._sendWithProtocol(this._createStreamItemMessage(n,e))))}})}}_replaceStreamingParams(e){const t=[],n=[];for(let o=0;o0)&&(t=!1,this._accessToken=await this._accessTokenFactory()),this._setAuthorizationHeader(e);const n=await this._innerClient.send(e);return t&&401===n.statusCode&&this._accessTokenFactory?(this._accessToken=await this._accessTokenFactory(),this._setAuthorizationHeader(e),await this._innerClient.send(e)):n}_setAuthorizationHeader(e){e.headers||(e.headers={}),this._accessToken?e.headers[Xt.Authorization]=`Bearer ${this._accessToken}`:this._accessTokenFactory&&e.headers[Xt.Authorization]&&delete e.headers[Xt.Authorization]}getCookieString(e){return this._innerClient.getCookieString(e)}}class Zt extends Gt{constructor(e){super(),this._logger=e;const t={_fetchType:void 0,_jar:void 0};var o;o=t,"undefined"==typeof fetch&&(o._jar=new(n(628).CookieJar),"undefined"==typeof fetch?o._fetchType=n(200):o._fetchType=fetch,o._fetchType=n(203)(o._fetchType,o._jar),1)?(this._fetchType=t._fetchType,this._jar=t._jar):this._fetchType=fetch.bind(function(){if("undefined"!=typeof globalThis)return globalThis;if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if(void 0!==n.g)return n.g;throw new Error("could not find global")}()),this._abortControllerType=AbortController;const r={_abortControllerType:this._abortControllerType};(function(e){return"undefined"==typeof AbortController&&(e._abortControllerType=n(778),!0)})(r)&&(this._abortControllerType=r._abortControllerType)}async send(e){if(e.abortSignal&&e.abortSignal.aborted)throw new Mt;if(!e.method)throw new Error("No method defined.");if(!e.url)throw new Error("No url defined.");const t=new this._abortControllerType;let n;e.abortSignal&&(e.abortSignal.onabort=()=>{t.abort(),n=new Mt});let o,r=null;if(e.timeout){const o=e.timeout;r=setTimeout((()=>{t.abort(),this._logger.log(vt.Warning,"Timeout from HTTP request."),n=new Ut}),o)}""===e.content&&(e.content=void 0),e.content&&(e.headers=e.headers||{},Et(e.content)?e.headers["Content-Type"]="application/octet-stream":e.headers["Content-Type"]="text/plain;charset=UTF-8");try{o=await this._fetchType(e.url,{body:e.content,cache:"no-cache",credentials:!0===e.withCredentials?"include":"same-origin",headers:{"X-Requested-With":"XMLHttpRequest",...e.headers},method:e.method,mode:"cors",redirect:"follow",signal:t.signal})}catch(e){if(n)throw n;throw this._logger.log(vt.Warning,`Error from HTTP request. ${e}.`),e}finally{r&&clearTimeout(r),e.abortSignal&&(e.abortSignal.onabort=null)}if(!o.ok){const e=await en(o,"text");throw new Nt(e||o.statusText,o.status)}const s=en(o,e.responseType),i=await s;return new Yt(o.status,o.statusText,i)}getCookieString(e){return""}}function en(e,t){let n;switch(t){case"arraybuffer":n=e.arrayBuffer();break;case"text":default:n=e.text();break;case"blob":case"document":case"json":throw new Error(`${t} is not supported.`)}return n}class tn extends Gt{constructor(e){super(),this._logger=e}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new Mt):e.method?e.url?new Promise(((t,n)=>{const o=new XMLHttpRequest;o.open(e.method,e.url,!0),o.withCredentials=void 0===e.withCredentials||e.withCredentials,o.setRequestHeader("X-Requested-With","XMLHttpRequest"),""===e.content&&(e.content=void 0),e.content&&(Et(e.content)?o.setRequestHeader("Content-Type","application/octet-stream"):o.setRequestHeader("Content-Type","text/plain;charset=UTF-8"));const r=e.headers;r&&Object.keys(r).forEach((e=>{o.setRequestHeader(e,r[e])})),e.responseType&&(o.responseType=e.responseType),e.abortSignal&&(e.abortSignal.onabort=()=>{o.abort(),n(new Mt)}),e.timeout&&(o.timeout=e.timeout),o.onload=()=>{e.abortSignal&&(e.abortSignal.onabort=null),o.status>=200&&o.status<300?t(new Yt(o.status,o.statusText,o.response||o.responseText)):n(new Nt(o.response||o.responseText||o.statusText,o.status))},o.onerror=()=>{this._logger.log(vt.Warning,`Error from HTTP request. ${o.status}: ${o.statusText}.`),n(new Nt(o.statusText,o.status))},o.ontimeout=()=>{this._logger.log(vt.Warning,"Timeout from HTTP request."),n(new Ut)},o.send(e.content)})):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}}class nn extends Gt{constructor(e){if(super(),"undefined"!=typeof fetch)this._httpClient=new Zt(e);else{if("undefined"==typeof XMLHttpRequest)throw new Error("No usable HttpClient found.");this._httpClient=new tn(e)}}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new Mt):e.method?e.url?this._httpClient.send(e):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}getCookieString(e){return this._httpClient.getCookieString(e)}}var on,rn;!function(e){e[e.None=0]="None",e[e.WebSockets=1]="WebSockets",e[e.ServerSentEvents=2]="ServerSentEvents",e[e.LongPolling=4]="LongPolling"}(on||(on={})),function(e){e[e.Text=1]="Text",e[e.Binary=2]="Binary"}(rn||(rn={}));class sn{constructor(){this._isAborted=!1,this.onabort=null}abort(){this._isAborted||(this._isAborted=!0,this.onabort&&this.onabort())}get signal(){return this}get aborted(){return this._isAborted}}class an{get pollAborted(){return this._pollAbort.aborted}constructor(e,t,n){this._httpClient=e,this._logger=t,this._pollAbort=new sn,this._options=n,this._running=!1,this.onreceive=null,this.onclose=null}async connect(e,t){if(_t.isRequired(e,"url"),_t.isRequired(t,"transferFormat"),_t.isIn(t,rn,"transferFormat"),this._url=e,this._logger.log(vt.Trace,"(LongPolling transport) Connecting."),t===rn.Binary&&"undefined"!=typeof XMLHttpRequest&&"string"!=typeof(new XMLHttpRequest).responseType)throw new Error("Binary protocols over XmlHttpRequest not implementing advanced features are not supported.");const[n,o]=Tt(),r={[n]:o,...this._options.headers},s={abortSignal:this._pollAbort.signal,headers:r,timeout:1e5,withCredentials:this._options.withCredentials};t===rn.Binary&&(s.responseType="arraybuffer");const i=`${e}&_=${Date.now()}`;this._logger.log(vt.Trace,`(LongPolling transport) polling: ${i}.`);const a=await this._httpClient.get(i,s);200!==a.statusCode?(this._logger.log(vt.Error,`(LongPolling transport) Unexpected response code: ${a.statusCode}.`),this._closeError=new Nt(a.statusText||"",a.statusCode),this._running=!1):this._running=!0,this._receiving=this._poll(this._url,s)}async _poll(e,t){try{for(;this._running;)try{const n=`${e}&_=${Date.now()}`;this._logger.log(vt.Trace,`(LongPolling transport) polling: ${n}.`);const o=await this._httpClient.get(n,t);204===o.statusCode?(this._logger.log(vt.Information,"(LongPolling transport) Poll terminated by server."),this._running=!1):200!==o.statusCode?(this._logger.log(vt.Error,`(LongPolling transport) Unexpected response code: ${o.statusCode}.`),this._closeError=new Nt(o.statusText||"",o.statusCode),this._running=!1):o.content?(this._logger.log(vt.Trace,`(LongPolling transport) data received. ${St(o.content,this._options.logMessageContent)}.`),this.onreceive&&this.onreceive(o.content)):this._logger.log(vt.Trace,"(LongPolling transport) Poll timed out, reissuing.")}catch(e){this._running?e instanceof Ut?this._logger.log(vt.Trace,"(LongPolling transport) Poll timed out, reissuing."):(this._closeError=e,this._running=!1):this._logger.log(vt.Trace,`(LongPolling transport) Poll errored after shutdown: ${e.message}`)}}finally{this._logger.log(vt.Trace,"(LongPolling transport) Polling complete."),this.pollAborted||this._raiseOnClose()}}async send(e){return this._running?Ct(this._logger,"LongPolling",this._httpClient,this._url,e,this._options):Promise.reject(new Error("Cannot send until the transport is connected"))}async stop(){this._logger.log(vt.Trace,"(LongPolling transport) Stopping polling."),this._running=!1,this._pollAbort.abort();try{await this._receiving,this._logger.log(vt.Trace,`(LongPolling transport) sending DELETE request to ${this._url}.`);const e={},[t,n]=Tt();e[t]=n;const o={headers:{...e,...this._options.headers},timeout:this._options.timeout,withCredentials:this._options.withCredentials};let r;try{await this._httpClient.delete(this._url,o)}catch(e){r=e}r?r instanceof Nt&&(404===r.statusCode?this._logger.log(vt.Trace,"(LongPolling transport) A 404 response was returned from sending a DELETE request."):this._logger.log(vt.Trace,`(LongPolling transport) Error sending a DELETE request: ${r}`)):this._logger.log(vt.Trace,"(LongPolling transport) DELETE request accepted.")}finally{this._logger.log(vt.Trace,"(LongPolling transport) Stop finished."),this._raiseOnClose()}}_raiseOnClose(){if(this.onclose){let e="(LongPolling transport) Firing onclose event.";this._closeError&&(e+=" Error: "+this._closeError),this._logger.log(vt.Trace,e),this.onclose(this._closeError)}}}class cn{constructor(e,t,n,o){this._httpClient=e,this._accessToken=t,this._logger=n,this._options=o,this.onreceive=null,this.onclose=null}async connect(e,t){return _t.isRequired(e,"url"),_t.isRequired(t,"transferFormat"),_t.isIn(t,rn,"transferFormat"),this._logger.log(vt.Trace,"(SSE transport) Connecting."),this._url=e,this._accessToken&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(this._accessToken)}`),new Promise(((n,o)=>{let r,s=!1;if(t===rn.Text){if(bt.isBrowser||bt.isWebWorker)r=new this._options.EventSource(e,{withCredentials:this._options.withCredentials});else{const t=this._httpClient.getCookieString(e),n={};n.Cookie=t;const[o,s]=Tt();n[o]=s,r=new this._options.EventSource(e,{withCredentials:this._options.withCredentials,headers:{...n,...this._options.headers}})}try{r.onmessage=e=>{if(this.onreceive)try{this._logger.log(vt.Trace,`(SSE transport) data received. ${St(e.data,this._options.logMessageContent)}.`),this.onreceive(e.data)}catch(e){return void this._close(e)}},r.onerror=e=>{s?this._close():o(new Error("EventSource failed to connect. The connection could not be found on the server, either the connection ID is not present on the server, or a proxy is refusing/buffering the connection. If you have multiple servers check that sticky sessions are enabled."))},r.onopen=()=>{this._logger.log(vt.Information,`SSE connected to ${this._url}`),this._eventSource=r,s=!0,n()}}catch(e){return void o(e)}}else o(new Error("The Server-Sent Events transport only supports the 'Text' transfer format"))}))}async send(e){return this._eventSource?Ct(this._logger,"SSE",this._httpClient,this._url,e,this._options):Promise.reject(new Error("Cannot send until the transport is connected"))}stop(){return this._close(),Promise.resolve()}_close(e){this._eventSource&&(this._eventSource.close(),this._eventSource=void 0,this.onclose&&this.onclose(e))}}class ln{constructor(e,t,n,o,r,s){this._logger=n,this._accessTokenFactory=t,this._logMessageContent=o,this._webSocketConstructor=r,this._httpClient=e,this.onreceive=null,this.onclose=null,this._headers=s}async connect(e,t){let n;return _t.isRequired(e,"url"),_t.isRequired(t,"transferFormat"),_t.isIn(t,rn,"transferFormat"),this._logger.log(vt.Trace,"(WebSockets transport) Connecting."),this._accessTokenFactory&&(n=await this._accessTokenFactory()),new Promise(((o,r)=>{let s;e=e.replace(/^http/,"ws");const i=this._httpClient.getCookieString(e);let a=!1;if(bt.isReactNative){const t={},[o,r]=Tt();t[o]=r,n&&(t[Xt.Authorization]=`Bearer ${n}`),i&&(t[Xt.Cookie]=i),s=new this._webSocketConstructor(e,void 0,{headers:{...t,...this._headers}})}else n&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(n)}`);s||(s=new this._webSocketConstructor(e)),t===rn.Binary&&(s.binaryType="arraybuffer"),s.onopen=t=>{this._logger.log(vt.Information,`WebSocket connected to ${e}.`),this._webSocket=s,a=!0,o()},s.onerror=e=>{let t=null;t="undefined"!=typeof ErrorEvent&&e instanceof ErrorEvent?e.error:"There was an error with the transport",this._logger.log(vt.Information,`(WebSockets transport) ${t}.`)},s.onmessage=e=>{if(this._logger.log(vt.Trace,`(WebSockets transport) data received. ${St(e.data,this._logMessageContent)}.`),this.onreceive)try{this.onreceive(e.data)}catch(e){return void this._close(e)}},s.onclose=e=>{if(a)this._close(e);else{let t=null;t="undefined"!=typeof ErrorEvent&&e instanceof ErrorEvent?e.error:"WebSocket failed to connect. The connection could not be found on the server, either the endpoint may not be a SignalR endpoint, the connection ID is not present on the server, or there is a proxy blocking WebSockets. If you have multiple servers check that sticky sessions are enabled.",r(new Error(t))}}}))}send(e){return this._webSocket&&this._webSocket.readyState===this._webSocketConstructor.OPEN?(this._logger.log(vt.Trace,`(WebSockets transport) sending data. ${St(e,this._logMessageContent)}.`),this._webSocket.send(e),Promise.resolve()):Promise.reject("WebSocket is not in the OPEN state")}stop(){return this._webSocket&&this._close(void 0),Promise.resolve()}_close(e){this._webSocket&&(this._webSocket.onclose=()=>{},this._webSocket.onmessage=()=>{},this._webSocket.onerror=()=>{},this._webSocket.close(),this._webSocket=void 0),this._logger.log(vt.Trace,"(WebSockets transport) socket closed."),this.onclose&&(!this._isCloseEvent(e)||!1!==e.wasClean&&1e3===e.code?e instanceof Error?this.onclose(e):this.onclose():this.onclose(new Error(`WebSocket closed with status code: ${e.code} (${e.reason||"no reason given"}).`)))}_isCloseEvent(e){return e&&"boolean"==typeof e.wasClean&&"number"==typeof e.code}}class hn{constructor(e,t={}){if(this._stopPromiseResolver=()=>{},this.features={},this._negotiateVersion=1,_t.isRequired(e,"url"),this._logger=function(e){return void 0===e?new kt(vt.Information):null===e?yt.instance:void 0!==e.log?e:new kt(e)}(t.logger),this.baseUrl=this._resolveUrl(e),(t=t||{}).logMessageContent=void 0!==t.logMessageContent&&t.logMessageContent,"boolean"!=typeof t.withCredentials&&void 0!==t.withCredentials)throw new Error("withCredentials option was not a 'boolean' or 'undefined' value");t.withCredentials=void 0===t.withCredentials||t.withCredentials,t.timeout=void 0===t.timeout?1e5:t.timeout,"undefined"==typeof WebSocket||t.WebSocket||(t.WebSocket=WebSocket),"undefined"==typeof EventSource||t.EventSource||(t.EventSource=EventSource),this._httpClient=new Qt(t.httpClient||new nn(this._logger),t.accessTokenFactory),this._connectionState="Disconnected",this._connectionStarted=!1,this._options=t,this.onreceive=null,this.onclose=null}async start(e){if(e=e||rn.Binary,_t.isIn(e,rn,"transferFormat"),this._logger.log(vt.Debug,`Starting connection with transfer format '${rn[e]}'.`),"Disconnected"!==this._connectionState)return Promise.reject(new Error("Cannot start an HttpConnection that is not in the 'Disconnected' state."));if(this._connectionState="Connecting",this._startInternalPromise=this._startInternal(e),await this._startInternalPromise,"Disconnecting"===this._connectionState){const e="Failed to start the HttpConnection before stop() was called.";return this._logger.log(vt.Error,e),await this._stopPromise,Promise.reject(new Mt(e))}if("Connected"!==this._connectionState){const e="HttpConnection.startInternal completed gracefully but didn't enter the connection into the connected state!";return this._logger.log(vt.Error,e),Promise.reject(new Mt(e))}this._connectionStarted=!0}send(e){return"Connected"!==this._connectionState?Promise.reject(new Error("Cannot send data if the connection is not in the 'Connected' State.")):(this._sendQueue||(this._sendQueue=new dn(this.transport)),this._sendQueue.send(e))}async stop(e){return"Disconnected"===this._connectionState?(this._logger.log(vt.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnected state.`),Promise.resolve()):"Disconnecting"===this._connectionState?(this._logger.log(vt.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnecting state.`),this._stopPromise):(this._connectionState="Disconnecting",this._stopPromise=new Promise((e=>{this._stopPromiseResolver=e})),await this._stopInternal(e),void await this._stopPromise)}async _stopInternal(e){this._stopError=e;try{await this._startInternalPromise}catch(e){}if(this.transport){try{await this.transport.stop()}catch(e){this._logger.log(vt.Error,`HttpConnection.transport.stop() threw error '${e}'.`),this._stopConnection()}this.transport=void 0}else this._logger.log(vt.Debug,"HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.")}async _startInternal(e){let t=this.baseUrl;this._accessTokenFactory=this._options.accessTokenFactory,this._httpClient._accessTokenFactory=this._accessTokenFactory;try{if(this._options.skipNegotiation){if(this._options.transport!==on.WebSockets)throw new Error("Negotiation can only be skipped when using the WebSocket transport directly.");this.transport=this._constructTransport(on.WebSockets),await this._startTransport(t,e)}else{let n=null,o=0;do{if(n=await this._getNegotiationResponse(t),"Disconnecting"===this._connectionState||"Disconnected"===this._connectionState)throw new Mt("The connection was stopped during negotiation.");if(n.error)throw new Error(n.error);if(n.ProtocolVersion)throw new Error("Detected a connection attempt to an ASP.NET SignalR Server. This client only supports connecting to an ASP.NET Core SignalR Server. See https://aka.ms/signalr-core-differences for details.");if(n.url&&(t=n.url),n.accessToken){const e=n.accessToken;this._accessTokenFactory=()=>e,this._httpClient._accessToken=e,this._httpClient._accessTokenFactory=void 0}o++}while(n.url&&o<100);if(100===o&&n.url)throw new Error("Negotiate redirection limit exceeded.");await this._createTransport(t,this._options.transport,n,e)}this.transport instanceof an&&(this.features.inherentKeepAlive=!0),"Connecting"===this._connectionState&&(this._logger.log(vt.Debug,"The HttpConnection connected successfully."),this._connectionState="Connected")}catch(e){return this._logger.log(vt.Error,"Failed to start the connection: "+e),this._connectionState="Disconnected",this.transport=void 0,this._stopPromiseResolver(),Promise.reject(e)}}async _getNegotiationResponse(e){const t={},[n,o]=Tt();t[n]=o;const r=this._resolveNegotiateUrl(e);this._logger.log(vt.Debug,`Sending negotiation request: ${r}.`);try{const e=await this._httpClient.post(r,{content:"",headers:{...t,...this._options.headers},timeout:this._options.timeout,withCredentials:this._options.withCredentials});if(200!==e.statusCode)return Promise.reject(new Error(`Unexpected status code returned from negotiate '${e.statusCode}'`));const n=JSON.parse(e.content);return(!n.negotiateVersion||n.negotiateVersion<1)&&(n.connectionToken=n.connectionId),n.useStatefulReconnect&&!0!==this._options._useStatefulReconnect?Promise.reject(new Ot("Client didn't negotiate Stateful Reconnect but the server did.")):n}catch(e){let t="Failed to complete negotiation with the server: "+e;return e instanceof Nt&&404===e.statusCode&&(t+=" Either this is not a SignalR endpoint or there is a proxy blocking the connection."),this._logger.log(vt.Error,t),Promise.reject(new Ot(t))}}_createConnectUrl(e,t){return t?e+(-1===e.indexOf("?")?"?":"&")+`id=${t}`:e}async _createTransport(e,t,n,o){let r=this._createConnectUrl(e,n.connectionToken);if(this._isITransport(t))return this._logger.log(vt.Debug,"Connection was provided an instance of ITransport, using that directly."),this.transport=t,await this._startTransport(r,o),void(this.connectionId=n.connectionId);const s=[],i=n.availableTransports||[];let a=n;for(const n of i){const i=this._resolveTransportOrError(n,t,o,!0===(null==a?void 0:a.useStatefulReconnect));if(i instanceof Error)s.push(`${n.transport} failed:`),s.push(i);else if(this._isITransport(i)){if(this.transport=i,!a){try{a=await this._getNegotiationResponse(e)}catch(e){return Promise.reject(e)}r=this._createConnectUrl(e,a.connectionToken)}try{return await this._startTransport(r,o),void(this.connectionId=a.connectionId)}catch(e){if(this._logger.log(vt.Error,`Failed to start the transport '${n.transport}': ${e}`),a=void 0,s.push(new $t(`${n.transport} failed: ${e}`,on[n.transport])),"Connecting"!==this._connectionState){const e="Failed to select transport before stop() was called.";return this._logger.log(vt.Debug,e),Promise.reject(new Mt(e))}}}}return s.length>0?Promise.reject(new Ft(`Unable to connect to the server with any of the available transports. ${s.join(" ")}`,s)):Promise.reject(new Error("None of the transports supported by the client are supported by the server."))}_constructTransport(e){switch(e){case on.WebSockets:if(!this._options.WebSocket)throw new Error("'WebSocket' is not supported in your environment.");return new ln(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent,this._options.WebSocket,this._options.headers||{});case on.ServerSentEvents:if(!this._options.EventSource)throw new Error("'EventSource' is not supported in your environment.");return new cn(this._httpClient,this._httpClient._accessToken,this._logger,this._options);case on.LongPolling:return new an(this._httpClient,this._logger,this._options);default:throw new Error(`Unknown transport: ${e}.`)}}_startTransport(e,t){return this.transport.onreceive=this.onreceive,this.features.reconnect?this.transport.onclose=async n=>{let o=!1;if(this.features.reconnect){try{this.features.disconnected(),await this.transport.connect(e,t),await this.features.resend()}catch{o=!0}o&&this._stopConnection(n)}else this._stopConnection(n)}:this.transport.onclose=e=>this._stopConnection(e),this.transport.connect(e,t)}_resolveTransportOrError(e,t,n,o){const r=on[e.transport];if(null==r)return this._logger.log(vt.Debug,`Skipping transport '${e.transport}' because it is not supported by this client.`),new Error(`Skipping transport '${e.transport}' because it is not supported by this client.`);if(!function(e,t){return!e||0!=(t&e)}(t,r))return this._logger.log(vt.Debug,`Skipping transport '${on[r]}' because it was disabled by the client.`),new Lt(`'${on[r]}' is disabled by the client.`,r);if(!(e.transferFormats.map((e=>rn[e])).indexOf(n)>=0))return this._logger.log(vt.Debug,`Skipping transport '${on[r]}' because it does not support the requested transfer format '${rn[n]}'.`),new Error(`'${on[r]}' does not support ${rn[n]}.`);if(r===on.WebSockets&&!this._options.WebSocket||r===on.ServerSentEvents&&!this._options.EventSource)return this._logger.log(vt.Debug,`Skipping transport '${on[r]}' because it is not supported in your environment.'`),new Bt(`'${on[r]}' is not supported in your environment.`,r);this._logger.log(vt.Debug,`Selecting transport '${on[r]}'.`);try{return this.features.reconnect=r===on.WebSockets?o:void 0,this._constructTransport(r)}catch(e){return e}}_isITransport(e){return e&&"object"==typeof e&&"connect"in e}_stopConnection(e){if(this._logger.log(vt.Debug,`HttpConnection.stopConnection(${e}) called while in state ${this._connectionState}.`),this.transport=void 0,e=this._stopError||e,this._stopError=void 0,"Disconnected"!==this._connectionState){if("Connecting"===this._connectionState)throw this._logger.log(vt.Warning,`Call to HttpConnection.stopConnection(${e}) was ignored because the connection is still in the connecting state.`),new Error(`HttpConnection.stopConnection(${e}) was called while the connection is still in the connecting state.`);if("Disconnecting"===this._connectionState&&this._stopPromiseResolver(),e?this._logger.log(vt.Error,`Connection disconnected with error '${e}'.`):this._logger.log(vt.Information,"Connection disconnected."),this._sendQueue&&(this._sendQueue.stop().catch((e=>{this._logger.log(vt.Error,`TransportSendQueue.stop() threw error '${e}'.`)})),this._sendQueue=void 0),this.connectionId=void 0,this._connectionState="Disconnected",this._connectionStarted){this._connectionStarted=!1;try{this.onclose&&this.onclose(e)}catch(t){this._logger.log(vt.Error,`HttpConnection.onclose(${e}) threw error '${t}'.`)}}}else this._logger.log(vt.Debug,`Call to HttpConnection.stopConnection(${e}) was ignored because the connection is already in the disconnected state.`)}_resolveUrl(e){if(0===e.lastIndexOf("https://",0)||0===e.lastIndexOf("http://",0))return e;if(!bt.isBrowser)throw new Error(`Cannot resolve '${e}'.`);const t=window.document.createElement("a");return t.href=e,this._logger.log(vt.Information,`Normalizing '${e}' to '${t.href}'.`),t.href}_resolveNegotiateUrl(e){const t=new URL(e);t.pathname.endsWith("/")?t.pathname+="negotiate":t.pathname+="/negotiate";const n=new URLSearchParams(t.searchParams);return n.has("negotiateVersion")||n.append("negotiateVersion",this._negotiateVersion.toString()),n.has("useStatefulReconnect")?"true"===n.get("useStatefulReconnect")&&(this._options._useStatefulReconnect=!0):!0===this._options._useStatefulReconnect&&n.append("useStatefulReconnect","true"),t.search=n.toString(),t.toString()}}class dn{constructor(e){this._transport=e,this._buffer=[],this._executing=!0,this._sendBufferedData=new un,this._transportResult=new un,this._sendLoopPromise=this._sendLoop()}send(e){return this._bufferData(e),this._transportResult||(this._transportResult=new un),this._transportResult.promise}stop(){return this._executing=!1,this._sendBufferedData.resolve(),this._sendLoopPromise}_bufferData(e){if(this._buffer.length&&typeof this._buffer[0]!=typeof e)throw new Error(`Expected data to be of type ${typeof this._buffer} but was of type ${typeof e}`);this._buffer.push(e),this._sendBufferedData.resolve()}async _sendLoop(){for(;;){if(await this._sendBufferedData.promise,!this._executing){this._transportResult&&this._transportResult.reject("Connection stopped.");break}this._sendBufferedData=new un;const e=this._transportResult;this._transportResult=void 0;const t="string"==typeof this._buffer[0]?this._buffer.join(""):dn._concatBuffers(this._buffer);this._buffer.length=0;try{await this._transport.send(t),e.resolve()}catch(t){e.reject(t)}}}static _concatBuffers(e){const t=e.map((e=>e.byteLength)).reduce(((e,t)=>e+t)),n=new Uint8Array(t);let o=0;for(const t of e)n.set(new Uint8Array(t),o),o+=t.byteLength;return n.buffer}}class un{constructor(){this.promise=new Promise(((e,t)=>[this._resolver,this._rejecter]=[e,t]))}resolve(){this._resolver()}reject(e){this._rejecter(e)}}class pn{constructor(){this.name="json",this.version=2,this.transferFormat=rn.Text}parseMessages(e,t){if("string"!=typeof e)throw new Error("Invalid input for JSON hub protocol. Expected a string.");if(!e)return[];null===t&&(t=yt.instance);const n=mt.parse(e),o=[];for(const e of n){const n=JSON.parse(e);if("number"!=typeof n.type)throw new Error("Invalid payload.");switch(n.type){case Ht.Invocation:this._isInvocationMessage(n);break;case Ht.StreamItem:this._isStreamItemMessage(n);break;case Ht.Completion:this._isCompletionMessage(n);break;case Ht.Ping:case Ht.Close:break;case Ht.Ack:this._isAckMessage(n);break;case Ht.Sequence:this._isSequenceMessage(n);break;default:t.log(vt.Information,"Unknown message type '"+n.type+"' ignored.");continue}o.push(n)}return o}writeMessage(e){return mt.write(JSON.stringify(e))}_isInvocationMessage(e){this._assertNotEmptyString(e.target,"Invalid payload for Invocation message."),void 0!==e.invocationId&&this._assertNotEmptyString(e.invocationId,"Invalid payload for Invocation message.")}_isStreamItemMessage(e){if(this._assertNotEmptyString(e.invocationId,"Invalid payload for StreamItem message."),void 0===e.item)throw new Error("Invalid payload for StreamItem message.")}_isCompletionMessage(e){if(e.result&&e.error)throw new Error("Invalid payload for Completion message.");!e.result&&e.error&&this._assertNotEmptyString(e.error,"Invalid payload for Completion message."),this._assertNotEmptyString(e.invocationId,"Invalid payload for Completion message.")}_isAckMessage(e){if("number"!=typeof e.sequenceId)throw new Error("Invalid SequenceId for Ack message.")}_isSequenceMessage(e){if("number"!=typeof e.sequenceId)throw new Error("Invalid SequenceId for Sequence message.")}_assertNotEmptyString(e,t){if("string"!=typeof e||""===e)throw new Error(t)}}const fn={trace:vt.Trace,debug:vt.Debug,info:vt.Information,information:vt.Information,warn:vt.Warning,warning:vt.Warning,error:vt.Error,critical:vt.Critical,none:vt.None};class gn{configureLogging(e){if(_t.isRequired(e,"logging"),function(e){return void 0!==e.log}(e))this.logger=e;else if("string"==typeof e){const t=function(e){const t=fn[e.toLowerCase()];if(void 0!==t)return t;throw new Error(`Unknown log level: ${e}`)}(e);this.logger=new kt(t)}else this.logger=new kt(e);return this}withUrl(e,t){return _t.isRequired(e,"url"),_t.isNotEmpty(e,"url"),this.url=e,this.httpConnectionOptions="object"==typeof t?{...this.httpConnectionOptions,...t}:{...this.httpConnectionOptions,transport:t},this}withHubProtocol(e){return _t.isRequired(e,"protocol"),this.protocol=e,this}withAutomaticReconnect(e){if(this.reconnectPolicy)throw new Error("A reconnectPolicy has already been set.");return e?Array.isArray(e)?this.reconnectPolicy=new Vt(e):this.reconnectPolicy=e:this.reconnectPolicy=new Vt,this}withServerTimeout(e){return _t.isRequired(e,"milliseconds"),this._serverTimeoutInMilliseconds=e,this}withKeepAliveInterval(e){return _t.isRequired(e,"milliseconds"),this._keepAliveIntervalInMilliseconds=e,this}withStatefulReconnect(e){return void 0===this.httpConnectionOptions&&(this.httpConnectionOptions={}),this.httpConnectionOptions._useStatefulReconnect=!0,this._statefulReconnectBufferSize=null==e?void 0:e.bufferSize,this}build(){const e=this.httpConnectionOptions||{};if(void 0===e.logger&&(e.logger=this.logger),!this.url)throw new Error("The 'HubConnectionBuilder.withUrl' method must be called before building the connection.");const t=new hn(this.url,e);return Jt.create(t,this.logger||yt.instance,this.protocol||new pn,this.reconnectPolicy,this._serverTimeoutInMilliseconds,this._keepAliveIntervalInMilliseconds,this._statefulReconnectBufferSize)}}var mn;!function(e){e[e.Default=0]="Default",e[e.Server=1]="Server",e[e.WebAssembly=2]="WebAssembly",e[e.WebView=3]="WebView"}(mn||(mn={}));var vn,yn,wn,_n=4294967295;function bn(e,t,n){var o=Math.floor(n/4294967296),r=n;e.setUint32(t,o),e.setUint32(t+4,r)}function Sn(e,t){return 4294967296*e.getInt32(t)+e.getUint32(t+4)}var En=("undefined"==typeof process||"never"!==(null===(vn=null===process||void 0===process?void 0:process.env)||void 0===vn?void 0:vn.TEXT_ENCODING))&&"undefined"!=typeof TextEncoder&&"undefined"!=typeof TextDecoder;function Cn(e){for(var t=e.length,n=0,o=0;o=55296&&r<=56319&&o65535&&(h-=65536,s.push(h>>>10&1023|55296),h=56320|1023&h),s.push(h)}else s.push(a);s.length>=4096&&(i+=String.fromCharCode.apply(String,s),s.length=0)}return s.length>0&&(i+=String.fromCharCode.apply(String,s)),i}var xn,Rn=En?new TextDecoder:null,Pn=En?"undefined"!=typeof process&&"force"!==(null===(wn=null===process||void 0===process?void 0:process.env)||void 0===wn?void 0:wn.TEXT_DECODER)?200:0:_n,An=function(e,t){this.type=e,this.data=t},Nn=(xn=function(e,t){return xn=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},xn(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function n(){this.constructor=e}xn(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),Un=function(e){function t(n){var o=e.call(this,n)||this,r=Object.create(t.prototype);return Object.setPrototypeOf(o,r),Object.defineProperty(o,"name",{configurable:!0,enumerable:!1,value:t.name}),o}return Nn(t,e),t}(Error),Mn={type:-1,encode:function(e){var t,n,o,r;return e instanceof Date?function(e){var t,n=e.sec,o=e.nsec;if(n>=0&&o>=0&&n<=17179869183){if(0===o&&n<=4294967295){var r=new Uint8Array(4);return(t=new DataView(r.buffer)).setUint32(0,n),r}var s=n/4294967296,i=4294967295&n;return r=new Uint8Array(8),(t=new DataView(r.buffer)).setUint32(0,o<<2|3&s),t.setUint32(4,i),r}return r=new Uint8Array(12),(t=new DataView(r.buffer)).setUint32(0,o),bn(t,4,n),r}((o=1e6*((t=e.getTime())-1e3*(n=Math.floor(t/1e3))),{sec:n+(r=Math.floor(o/1e9)),nsec:o-1e9*r})):null},decode:function(e){var t=function(e){var t=new DataView(e.buffer,e.byteOffset,e.byteLength);switch(e.byteLength){case 4:return{sec:t.getUint32(0),nsec:0};case 8:var n=t.getUint32(0);return{sec:4294967296*(3&n)+t.getUint32(4),nsec:n>>>2};case 12:return{sec:Sn(t,4),nsec:t.getUint32(0)};default:throw new Un("Unrecognized data size for timestamp (expected 4, 8, or 12): ".concat(e.length))}}(e);return new Date(1e3*t.sec+t.nsec/1e6)}},Bn=function(){function e(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(Mn)}return e.prototype.register=function(e){var t=e.type,n=e.encode,o=e.decode;if(t>=0)this.encoders[t]=n,this.decoders[t]=o;else{var r=1+t;this.builtInEncoders[r]=n,this.builtInDecoders[r]=o}},e.prototype.tryToEncode=function(e,t){for(var n=0;nthis.maxDepth)throw new Error("Too deep objects in depth ".concat(t));null==e?this.encodeNil():"boolean"==typeof e?this.encodeBoolean(e):"number"==typeof e?this.encodeNumber(e):"string"==typeof e?this.encodeString(e):this.encodeObject(e,t)},e.prototype.ensureBufferSizeToWrite=function(e){var t=this.pos+e;this.view.byteLength=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):(this.writeU8(211),this.writeI64(e)):this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))},e.prototype.writeStringHeader=function(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else{if(!(e<4294967296))throw new Error("Too long string: ".concat(e," bytes in UTF-8"));this.writeU8(219),this.writeU32(e)}},e.prototype.encodeString=function(e){if(e.length>kn){var t=Cn(e);this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),Tn(e,this.bytes,this.pos),this.pos+=t}else t=Cn(e),this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),function(e,t,n){for(var o=e.length,r=n,s=0;s>6&31|192;else{if(i>=55296&&i<=56319&&s>12&15|224,t[r++]=i>>6&63|128):(t[r++]=i>>18&7|240,t[r++]=i>>12&63|128,t[r++]=i>>6&63|128)}t[r++]=63&i|128}else t[r++]=i}}(e,this.bytes,this.pos),this.pos+=t},e.prototype.encodeObject=function(e,t){var n=this.extensionCodec.tryToEncode(e,this.context);if(null!=n)this.encodeExtension(n);else if(Array.isArray(e))this.encodeArray(e,t);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else{if("object"!=typeof e)throw new Error("Unrecognized object: ".concat(Object.prototype.toString.apply(e)));this.encodeMap(e,t)}},e.prototype.encodeBinary=function(e){var t=e.byteLength;if(t<256)this.writeU8(196),this.writeU8(t);else if(t<65536)this.writeU8(197),this.writeU16(t);else{if(!(t<4294967296))throw new Error("Too large binary: ".concat(t));this.writeU8(198),this.writeU32(t)}var n=Ln(e);this.writeU8a(n)},e.prototype.encodeArray=function(e,t){var n=e.length;if(n<16)this.writeU8(144+n);else if(n<65536)this.writeU8(220),this.writeU16(n);else{if(!(n<4294967296))throw new Error("Too large array: ".concat(n));this.writeU8(221),this.writeU32(n)}for(var o=0,r=e;o0&&e<=this.maxKeyLength},e.prototype.find=function(e,t,n){e:for(var o=0,r=this.caches[n-1];o=this.maxLengthPerKey?n[Math.random()*n.length|0]=o:n.push(o)},e.prototype.decode=function(e,t,n){var o=this.find(e,t,n);if(null!=o)return this.hit++,o;this.miss++;var r=Dn(e,t,n),s=Uint8Array.prototype.slice.call(e,t,t+n);return this.store(s,r),r},e}(),Hn=function(e,t){var n,o,r,s,i={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(s){return function(a){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;i;)try{if(n=1,o&&(r=2&s[0]?o.return:s[0]?o.throw||((r=o.return)&&r.call(o),0):o.next)&&!(r=r.call(o,s[1])).done)return r;switch(o=0,r&&(s=[2&s[0],r.value]),s[0]){case 0:case 1:r=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,o=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!((r=(r=i.trys).length>0&&r[r.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!r||s[1]>r[0]&&s[1]=e},e.prototype.createExtraByteError=function(e){var t=this.view,n=this.pos;return new RangeError("Extra ".concat(t.byteLength-n," of ").concat(t.byteLength," byte(s) found at buffer[").concat(e,"]"))},e.prototype.decode=function(e){this.reinitializeState(),this.setBuffer(e);var t=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return t},e.prototype.decodeMulti=function(e){return Hn(this,(function(t){switch(t.label){case 0:this.reinitializeState(),this.setBuffer(e),t.label=1;case 1:return this.hasRemaining(1)?[4,this.doDecodeSync()]:[3,3];case 2:return t.sent(),[3,1];case 3:return[2]}}))},e.prototype.decodeAsync=function(e){var t,n,o,r,s,i,a;return s=this,void 0,a=function(){var s,i,a,c,l,h,d,u;return Hn(this,(function(p){switch(p.label){case 0:s=!1,p.label=1;case 1:p.trys.push([1,6,7,12]),t=jn(e),p.label=2;case 2:return[4,t.next()];case 3:if((n=p.sent()).done)return[3,5];if(a=n.value,s)throw this.createExtraByteError(this.totalPos);this.appendBuffer(a);try{i=this.doDecodeSync(),s=!0}catch(e){if(!(e instanceof Jn))throw e}this.totalPos+=this.pos,p.label=4;case 4:return[3,2];case 5:return[3,12];case 6:return c=p.sent(),o={error:c},[3,12];case 7:return p.trys.push([7,,10,11]),n&&!n.done&&(r=t.return)?[4,r.call(t)]:[3,9];case 8:p.sent(),p.label=9;case 9:return[3,11];case 10:if(o)throw o.error;return[7];case 11:return[7];case 12:if(s){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return[2,i]}throw h=(l=this).headByte,d=l.pos,u=l.totalPos,new RangeError("Insufficient data in parsing ".concat(On(h)," at ").concat(u," (").concat(d," in the current buffer)"))}}))},new((i=void 0)||(i=Promise))((function(e,t){function n(e){try{r(a.next(e))}catch(e){t(e)}}function o(e){try{r(a.throw(e))}catch(e){t(e)}}function r(t){var r;t.done?e(t.value):(r=t.value,r instanceof i?r:new i((function(e){e(r)}))).then(n,o)}r((a=a.apply(s,[])).next())}))},e.prototype.decodeArrayStream=function(e){return this.decodeMultiAsync(e,!0)},e.prototype.decodeStream=function(e){return this.decodeMultiAsync(e,!1)},e.prototype.decodeMultiAsync=function(e,t){return function(n,o,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var s,i=function(){var n,o,r,s,i,a,c,l,h;return Hn(this,(function(d){switch(d.label){case 0:n=t,o=-1,d.label=1;case 1:d.trys.push([1,13,14,19]),r=jn(e),d.label=2;case 2:return[4,Wn(r.next())];case 3:if((s=d.sent()).done)return[3,12];if(i=s.value,t&&0===o)throw this.createExtraByteError(this.totalPos);this.appendBuffer(i),n&&(o=this.readArraySize(),n=!1,this.complete()),d.label=4;case 4:d.trys.push([4,9,,10]),d.label=5;case 5:return[4,Wn(this.doDecodeSync())];case 6:return[4,d.sent()];case 7:return d.sent(),0==--o?[3,8]:[3,5];case 8:return[3,10];case 9:if(!((a=d.sent())instanceof Jn))throw a;return[3,10];case 10:this.totalPos+=this.pos,d.label=11;case 11:return[3,2];case 12:return[3,19];case 13:return c=d.sent(),l={error:c},[3,19];case 14:return d.trys.push([14,,17,18]),s&&!s.done&&(h=r.return)?[4,Wn(h.call(r))]:[3,16];case 15:d.sent(),d.label=16;case 16:return[3,18];case 17:if(l)throw l.error;return[7];case 18:return[7];case 19:return[2]}}))}.apply(n,o||[]),a=[];return s={},c("next"),c("throw"),c("return"),s[Symbol.asyncIterator]=function(){return this},s;function c(e){i[e]&&(s[e]=function(t){return new Promise((function(n,o){a.push([e,t,n,o])>1||l(e,t)}))})}function l(e,t){try{(n=i[e](t)).value instanceof Wn?Promise.resolve(n.value.v).then(h,d):u(a[0][2],n)}catch(e){u(a[0][3],e)}var n}function h(e){l("next",e)}function d(e){l("throw",e)}function u(e,t){e(t),a.shift(),a.length&&l(a[0][0],a[0][1])}}(this,arguments)},e.prototype.doDecodeSync=function(){e:for(;;){var e=this.readHeadByte(),t=void 0;if(e>=224)t=e-256;else if(e<192)if(e<128)t=e;else if(e<144){if(0!=(o=e-128)){this.pushMapState(o),this.complete();continue e}t={}}else if(e<160){if(0!=(o=e-144)){this.pushArrayState(o),this.complete();continue e}t=[]}else{var n=e-160;t=this.decodeUtf8String(n,0)}else if(192===e)t=null;else if(194===e)t=!1;else if(195===e)t=!0;else if(202===e)t=this.readF32();else if(203===e)t=this.readF64();else if(204===e)t=this.readU8();else if(205===e)t=this.readU16();else if(206===e)t=this.readU32();else if(207===e)t=this.readU64();else if(208===e)t=this.readI8();else if(209===e)t=this.readI16();else if(210===e)t=this.readI32();else if(211===e)t=this.readI64();else if(217===e)n=this.lookU8(),t=this.decodeUtf8String(n,1);else if(218===e)n=this.lookU16(),t=this.decodeUtf8String(n,2);else if(219===e)n=this.lookU32(),t=this.decodeUtf8String(n,4);else if(220===e){if(0!==(o=this.readU16())){this.pushArrayState(o),this.complete();continue e}t=[]}else if(221===e){if(0!==(o=this.readU32())){this.pushArrayState(o),this.complete();continue e}t=[]}else if(222===e){if(0!==(o=this.readU16())){this.pushMapState(o),this.complete();continue e}t={}}else if(223===e){if(0!==(o=this.readU32())){this.pushMapState(o),this.complete();continue e}t={}}else if(196===e){var o=this.lookU8();t=this.decodeBinary(o,1)}else if(197===e)o=this.lookU16(),t=this.decodeBinary(o,2);else if(198===e)o=this.lookU32(),t=this.decodeBinary(o,4);else if(212===e)t=this.decodeExtension(1,0);else if(213===e)t=this.decodeExtension(2,0);else if(214===e)t=this.decodeExtension(4,0);else if(215===e)t=this.decodeExtension(8,0);else if(216===e)t=this.decodeExtension(16,0);else if(199===e)o=this.lookU8(),t=this.decodeExtension(o,1);else if(200===e)o=this.lookU16(),t=this.decodeExtension(o,2);else{if(201!==e)throw new Un("Unrecognized type byte: ".concat(On(e)));o=this.lookU32(),t=this.decodeExtension(o,4)}this.complete();for(var r=this.stack;r.length>0;){var s=r[r.length-1];if(0===s.type){if(s.array[s.position]=t,s.position++,s.position!==s.size)continue e;r.pop(),t=s.array}else{if(1===s.type){if("string"!=(i=typeof t)&&"number"!==i)throw new Un("The type of key must be string or number but "+typeof t);if("__proto__"===t)throw new Un("The key __proto__ is not allowed");s.key=t,s.type=2;continue e}if(s.map[s.key]=t,s.readCount++,s.readCount!==s.size){s.key=null,s.type=1;continue e}r.pop(),t=s.map}}return t}var i},e.prototype.readHeadByte=function(){return-1===this.headByte&&(this.headByte=this.readU8()),this.headByte},e.prototype.complete=function(){this.headByte=-1},e.prototype.readArraySize=function(){var e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:if(e<160)return e-144;throw new Un("Unrecognized array type byte: ".concat(On(e)))}},e.prototype.pushMapState=function(e){if(e>this.maxMapLength)throw new Un("Max length exceeded: map length (".concat(e,") > maxMapLengthLength (").concat(this.maxMapLength,")"));this.stack.push({type:1,size:e,key:null,readCount:0,map:{}})},e.prototype.pushArrayState=function(e){if(e>this.maxArrayLength)throw new Un("Max length exceeded: array length (".concat(e,") > maxArrayLength (").concat(this.maxArrayLength,")"));this.stack.push({type:0,size:e,array:new Array(e),position:0})},e.prototype.decodeUtf8String=function(e,t){var n;if(e>this.maxStrLength)throw new Un("Max length exceeded: UTF-8 byte length (".concat(e,") > maxStrLength (").concat(this.maxStrLength,")"));if(this.bytes.byteLengthPn?function(e,t,n){var o=e.subarray(t,t+n);return Rn.decode(o)}(this.bytes,r,e):Dn(this.bytes,r,e),this.pos+=t+e,o},e.prototype.stateIsMapKey=function(){return this.stack.length>0&&1===this.stack[this.stack.length-1].type},e.prototype.decodeBinary=function(e,t){if(e>this.maxBinLength)throw new Un("Max length exceeded: bin length (".concat(e,") > maxBinLength (").concat(this.maxBinLength,")"));if(!this.hasRemaining(e+t))throw Kn;var n=this.pos+t,o=this.bytes.subarray(n,n+e);return this.pos+=t+e,o},e.prototype.decodeExtension=function(e,t){if(e>this.maxExtLength)throw new Un("Max length exceeded: ext length (".concat(e,") > maxExtLength (").concat(this.maxExtLength,")"));var n=this.view.getInt8(this.pos+t),o=this.decodeBinary(e,t+1);return this.extensionCodec.decode(o,n,this.context)},e.prototype.lookU8=function(){return this.view.getUint8(this.pos)},e.prototype.lookU16=function(){return this.view.getUint16(this.pos)},e.prototype.lookU32=function(){return this.view.getUint32(this.pos)},e.prototype.readU8=function(){var e=this.view.getUint8(this.pos);return this.pos++,e},e.prototype.readI8=function(){var e=this.view.getInt8(this.pos);return this.pos++,e},e.prototype.readU16=function(){var e=this.view.getUint16(this.pos);return this.pos+=2,e},e.prototype.readI16=function(){var e=this.view.getInt16(this.pos);return this.pos+=2,e},e.prototype.readU32=function(){var e=this.view.getUint32(this.pos);return this.pos+=4,e},e.prototype.readI32=function(){var e=this.view.getInt32(this.pos);return this.pos+=4,e},e.prototype.readU64=function(){var e,t,n=(e=this.view,t=this.pos,4294967296*e.getUint32(t)+e.getUint32(t+4));return this.pos+=8,n},e.prototype.readI64=function(){var e=Sn(this.view,this.pos);return this.pos+=8,e},e.prototype.readF32=function(){var e=this.view.getFloat32(this.pos);return this.pos+=4,e},e.prototype.readF64=function(){var e=this.view.getFloat64(this.pos);return this.pos+=8,e},e}();class Yn{static write(e){let t=e.byteLength||e.length;const n=[];do{let e=127&t;t>>=7,t>0&&(e|=128),n.push(e)}while(t>0);t=e.byteLength||e.length;const o=new Uint8Array(n.length+t);return o.set(n,0),o.set(e,n.length),o.buffer}static parse(e){const t=[],n=new Uint8Array(e),o=[0,7,14,21,28];for(let r=0;r7)throw new Error("Messages bigger than 2GB are not supported.");if(!(n.byteLength>=r+i+a))throw new Error("Incomplete message.");t.push(n.slice?n.slice(r+i,r+i+a):n.subarray(r+i,r+i+a)),r=r+i+a}return t}}const Gn=new Uint8Array([145,Ht.Ping]);class Qn{constructor(e){this.name="messagepack",this.version=2,this.transferFormat=rn.Binary,this._errorResult=1,this._voidResult=2,this._nonVoidResult=3,e=e||{},this._encoder=new $n(e.extensionCodec,e.context,e.maxDepth,e.initialBufferSize,e.sortKeys,e.forceFloat32,e.ignoreUndefined,e.forceIntegerToFloat),this._decoder=new Xn(e.extensionCodec,e.context,e.maxStrLength,e.maxBinLength,e.maxArrayLength,e.maxMapLength,e.maxExtLength)}parseMessages(e,t){if(!(n=e)||"undefined"==typeof ArrayBuffer||!(n instanceof ArrayBuffer||n.constructor&&"ArrayBuffer"===n.constructor.name))throw new Error("Invalid input for MessagePack hub protocol. Expected an ArrayBuffer.");var n;null===t&&(t=yt.instance);const o=Yn.parse(e),r=[];for(const e of o){const n=this._parseMessage(e,t);n&&r.push(n)}return r}writeMessage(e){switch(e.type){case Ht.Invocation:return this._writeInvocation(e);case Ht.StreamInvocation:return this._writeStreamInvocation(e);case Ht.StreamItem:return this._writeStreamItem(e);case Ht.Completion:return this._writeCompletion(e);case Ht.Ping:return Yn.write(Gn);case Ht.CancelInvocation:return this._writeCancelInvocation(e);case Ht.Close:return this._writeClose();case Ht.Ack:return this._writeAck(e);case Ht.Sequence:return this._writeSequence(e);default:throw new Error("Invalid message type.")}}_parseMessage(e,t){if(0===e.length)throw new Error("Invalid payload.");const n=this._decoder.decode(e);if(0===n.length||!(n instanceof Array))throw new Error("Invalid payload.");const o=n[0];switch(o){case Ht.Invocation:return this._createInvocationMessage(this._readHeaders(n),n);case Ht.StreamItem:return this._createStreamItemMessage(this._readHeaders(n),n);case Ht.Completion:return this._createCompletionMessage(this._readHeaders(n),n);case Ht.Ping:return this._createPingMessage(n);case Ht.Close:return this._createCloseMessage(n);case Ht.Ack:return this._createAckMessage(n);case Ht.Sequence:return this._createSequenceMessage(n);default:return t.log(vt.Information,"Unknown message type '"+o+"' ignored."),null}}_createCloseMessage(e){if(e.length<2)throw new Error("Invalid payload for Close message.");return{allowReconnect:e.length>=3?e[2]:void 0,error:e[1],type:Ht.Close}}_createPingMessage(e){if(e.length<1)throw new Error("Invalid payload for Ping message.");return{type:Ht.Ping}}_createInvocationMessage(e,t){if(t.length<5)throw new Error("Invalid payload for Invocation message.");const n=t[2];return n?{arguments:t[4],headers:e,invocationId:n,streamIds:[],target:t[3],type:Ht.Invocation}:{arguments:t[4],headers:e,streamIds:[],target:t[3],type:Ht.Invocation}}_createStreamItemMessage(e,t){if(t.length<4)throw new Error("Invalid payload for StreamItem message.");return{headers:e,invocationId:t[2],item:t[3],type:Ht.StreamItem}}_createCompletionMessage(e,t){if(t.length<4)throw new Error("Invalid payload for Completion message.");const n=t[3];if(n!==this._voidResult&&t.length<5)throw new Error("Invalid payload for Completion message.");let o,r;switch(n){case this._errorResult:o=t[4];break;case this._nonVoidResult:r=t[4]}return{error:o,headers:e,invocationId:t[2],result:r,type:Ht.Completion}}_createAckMessage(e){if(e.length<1)throw new Error("Invalid payload for Ack message.");return{sequenceId:e[1],type:Ht.Ack}}_createSequenceMessage(e){if(e.length<1)throw new Error("Invalid payload for Sequence message.");return{sequenceId:e[1],type:Ht.Sequence}}_writeInvocation(e){let t;return t=e.streamIds?this._encoder.encode([Ht.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments,e.streamIds]):this._encoder.encode([Ht.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments]),Yn.write(t.slice())}_writeStreamInvocation(e){let t;return t=e.streamIds?this._encoder.encode([Ht.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments,e.streamIds]):this._encoder.encode([Ht.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments]),Yn.write(t.slice())}_writeStreamItem(e){const t=this._encoder.encode([Ht.StreamItem,e.headers||{},e.invocationId,e.item]);return Yn.write(t.slice())}_writeCompletion(e){const t=e.error?this._errorResult:void 0!==e.result?this._nonVoidResult:this._voidResult;let n;switch(t){case this._errorResult:n=this._encoder.encode([Ht.Completion,e.headers||{},e.invocationId,t,e.error]);break;case this._voidResult:n=this._encoder.encode([Ht.Completion,e.headers||{},e.invocationId,t]);break;case this._nonVoidResult:n=this._encoder.encode([Ht.Completion,e.headers||{},e.invocationId,t,e.result])}return Yn.write(n.slice())}_writeCancelInvocation(e){const t=this._encoder.encode([Ht.CancelInvocation,e.headers||{},e.invocationId]);return Yn.write(t.slice())}_writeClose(){const e=this._encoder.encode([Ht.Close,null]);return Yn.write(e.slice())}_writeAck(e){const t=this._encoder.encode([Ht.Ack,e.sequenceId]);return Yn.write(t.slice())}_writeSequence(e){const t=this._encoder.encode([Ht.Sequence,e.sequenceId]);return Yn.write(t.slice())}_readHeaders(e){const t=e[1];if("object"!=typeof t)throw new Error("Invalid headers.");return t}}const Zn="function"==typeof TextDecoder?new TextDecoder("utf-8"):null,eo=Zn?Zn.decode.bind(Zn):function(e){let t=0;const n=e.length,o=[],r=[];for(;t65535&&(r-=65536,o.push(r>>>10&1023|55296),r=56320|1023&r),o.push(r)}o.length>1024&&(r.push(String.fromCharCode.apply(null,o)),o.length=0)}return r.push(String.fromCharCode.apply(null,o)),r.join("")},to=Math.pow(2,32),no=Math.pow(2,21)-1;function oo(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function ro(e,t){return e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24>>>0)}function so(e,t){const n=ro(e,t+4);if(n>no)throw new Error(`Cannot read uint64 with high order part ${n}, because the result would exceed Number.MAX_SAFE_INTEGER.`);return n*to+ro(e,t)}class io{constructor(e){this.batchData=e;const t=new ho(e);this.arrayRangeReader=new uo(e),this.arrayBuilderSegmentReader=new po(e),this.diffReader=new ao(e),this.editReader=new co(e,t),this.frameReader=new lo(e,t)}updatedComponents(){return oo(this.batchData,this.batchData.length-20)}referenceFrames(){return oo(this.batchData,this.batchData.length-16)}disposedComponentIds(){return oo(this.batchData,this.batchData.length-12)}disposedEventHandlerIds(){return oo(this.batchData,this.batchData.length-8)}updatedComponentsEntry(e,t){const n=e+4*t;return oo(this.batchData,n)}referenceFramesEntry(e,t){return e+20*t}disposedComponentIdsEntry(e,t){const n=e+4*t;return oo(this.batchData,n)}disposedEventHandlerIdsEntry(e,t){const n=e+8*t;return so(this.batchData,n)}}class ao{constructor(e){this.batchDataUint8=e}componentId(e){return oo(this.batchDataUint8,e)}edits(e){return e+4}editsEntry(e,t){return e+16*t}}class co{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}editType(e){return oo(this.batchDataUint8,e)}siblingIndex(e){return oo(this.batchDataUint8,e+4)}newTreeIndex(e){return oo(this.batchDataUint8,e+8)}moveToSiblingIndex(e){return oo(this.batchDataUint8,e+8)}removedAttributeName(e){const t=oo(this.batchDataUint8,e+12);return this.stringReader.readString(t)}}class lo{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}frameType(e){return oo(this.batchDataUint8,e)}subtreeLength(e){return oo(this.batchDataUint8,e+4)}elementReferenceCaptureId(e){const t=oo(this.batchDataUint8,e+4);return this.stringReader.readString(t)}componentId(e){return oo(this.batchDataUint8,e+8)}elementName(e){const t=oo(this.batchDataUint8,e+8);return this.stringReader.readString(t)}textContent(e){const t=oo(this.batchDataUint8,e+4);return this.stringReader.readString(t)}markupContent(e){const t=oo(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeName(e){const t=oo(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeValue(e){const t=oo(this.batchDataUint8,e+8);return this.stringReader.readString(t)}attributeEventHandlerId(e){return so(this.batchDataUint8,e+12)}}class ho{constructor(e){this.batchDataUint8=e,this.stringTableStartIndex=oo(e,e.length-4)}readString(e){if(-1===e)return null;{const n=oo(this.batchDataUint8,this.stringTableStartIndex+4*e),o=function(e,t){let n=0,o=0;for(let r=0;r<4;r++){const s=e[t+r];if(n|=(127&s)<this.nextBatchId)return this.fatalError?(this.logger.log(ot.Debug,`Received a new batch ${e} but errored out on a previous batch ${this.nextBatchId-1}`),void await n.send("OnRenderCompleted",this.nextBatchId-1,this.fatalError.toString())):void this.logger.log(ot.Debug,`Waiting for batch ${this.nextBatchId}. Batch ${e} not processed.`);try{this.nextBatchId++,this.logger.log(ot.Debug,`Applying batch ${e}.`),function(e,t){const n=fe[e];if(!n)throw new Error(`There is no browser renderer with ID ${e}.`);const o=t.arrayRangeReader,r=t.updatedComponents(),s=o.values(r),i=o.count(r),a=t.referenceFrames(),c=o.values(a),l=t.diffReader;for(let e=0;e{e.onclick=function(e){location.reload(),e.preventDefault()}})),document.querySelectorAll("#blazor-error-ui .dismiss").forEach((e=>{e.onclick=function(e){const t=document.querySelector("#blazor-error-ui");t&&(t.style.display="none"),e.preventDefault()}})))}class vo{constructor(t,n,o,r){this._firstUpdate=!0,this._renderingFailed=!1,this._disposed=!1,this._circuitId=void 0,this._applicationState=n,this._componentManager=t,this._options=o,this._logger=r,this._renderQueue=new fo(this._logger),this._dispatcher=e.attachDispatcher(this)}start(){if(this.isDisposedOrDisposing())throw new Error("Cannot start a disposed circuit.");return this._startPromise||(this._startPromise=this.startCore()),this._startPromise}updateRootComponents(e){var t,n;return this._firstUpdate?(this._firstUpdate=!1,null===(t=this._connection)||void 0===t?void 0:t.send("UpdateRootComponents",e,this._applicationState)):null===(n=this._connection)||void 0===n?void 0:n.send("UpdateRootComponents",e,"")}async startCore(){if(this._connection=await this.startConnection(),this._connection.state!==jt.Connected)return!1;const e=JSON.stringify(this._componentManager.initialComponents.map((e=>{return t=e,{...t,start:void 0,end:void 0};var t})));return this._circuitId=await this._connection.invoke("StartCircuit",Ne.getBaseURI(),Ne.getLocationHref(),e,this._applicationState||""),!!this._circuitId}async startConnection(){var e,t;const n=new Qn;n.name="blazorpack";const o=(new gn).withUrl("_blazor").withHubProtocol(n);this._options.configureSignalR(o);const r=o.build();r.on("JS.AttachComponent",((e,t)=>function(e,t,n,o){let r=fe[e];r||(r=new he(e),fe[e]=r),r.attachRootComponentToLogicalElement(n,t,!1)}(mn.Server,this.resolveElement(t,e),e))),r.on("JS.BeginInvokeJS",this._dispatcher.beginInvokeJSFromDotNet.bind(this._dispatcher)),r.on("JS.EndInvokeDotNet",this._dispatcher.endInvokeDotNetFromJS.bind(this._dispatcher)),r.on("JS.ReceiveByteArray",this._dispatcher.receiveByteArray.bind(this._dispatcher)),r.on("JS.BeginTransmitStream",(e=>{const t=new ReadableStream({start:t=>{r.stream("SendDotNetStreamToJS",e).subscribe({next:e=>t.enqueue(e),complete:()=>t.close(),error:e=>t.error(e)})}});this._dispatcher.supplyDotNetStream(e,t)})),r.on("JS.RenderBatch",(async(e,t)=>{var n,o;this._logger.log(vt.Debug,`Received render batch with id ${e} and ${t.byteLength} bytes.`),await this._renderQueue.processBatch(e,t,this._connection),null===(o=(n=this._componentManager).onAfterRenderBatch)||void 0===o||o.call(n,mn.Server)})),r.on("JS.EndLocationChanging",nt._internal.navigationManager.endLocationChanging),r.onclose((e=>!this._disposed&&!this._renderingFailed&&this._options.reconnectionHandler.onConnectionDown(this._options.reconnectionOptions,e))),r.on("JS.Error",(e=>{this._renderingFailed=!0,this.unhandledError(e),mo()}));try{await r.start()}catch(e){if(this.unhandledError(e),"FailedToNegotiateWithServerError"===e.errorType)throw e;mo(),e.innerErrors&&(e.innerErrors.some((e=>"UnsupportedTransportError"===e.errorType&&e.transport===on.WebSockets))?this._logger.log(vt.Error,"Unable to connect, please ensure you are using an updated browser that supports WebSockets."):e.innerErrors.some((e=>"FailedToStartTransportError"===e.errorType&&e.transport===on.WebSockets))?this._logger.log(vt.Error,"Unable to connect, please ensure WebSockets are available. A VPN or proxy may be blocking the connection."):e.innerErrors.some((e=>"DisabledTransportError"===e.errorType&&e.transport===on.LongPolling))&&this._logger.log(vt.Error,"Unable to initiate a SignalR connection to the server. This might be because the server is not configured to support WebSockets. For additional details, visit https://aka.ms/blazor-server-websockets-error."))}return(null===(t=null===(e=r.connection)||void 0===e?void 0:e.features)||void 0===t?void 0:t.inherentKeepAlive)&&this._logger.log(vt.Warning,"Failed to connect via WebSockets, using the Long Polling fallback transport. This may be due to a VPN or proxy blocking the connection. To troubleshoot this, visit https://aka.ms/blazor-server-using-fallback-long-polling."),r}async disconnect(){var e;await(null===(e=this._connection)||void 0===e?void 0:e.stop())}async reconnect(){if(!this._circuitId)throw new Error("Circuit host not initialized.");return this._connection.state===jt.Connected||(this._connection=await this.startConnection(),!!await this._connection.invoke("ConnectCircuit",this._circuitId)&&(this._options.reconnectionHandler.onConnectionUp(),!0))}beginInvokeDotNetFromJS(e,t,n,o,r){this.throwIfDispatchingWhenDisposed(),this._connection.send("BeginInvokeDotNetFromJS",e?e.toString():null,t,n,o||0,r)}endInvokeJSFromDotNet(e,t,n){this.throwIfDispatchingWhenDisposed(),this._connection.send("EndInvokeJSFromDotNet",e,t,n)}sendByteArray(e,t){this.throwIfDispatchingWhenDisposed(),this._connection.send("ReceiveByteArray",e,t)}throwIfDispatchingWhenDisposed(){if(this._disposed)throw new Error("The circuit associated with this dispatcher is no longer available.")}sendLocationChanged(e,t,n){return this._connection.send("OnLocationChanged",e,t,n)}sendLocationChanging(e,t,n,o){return this._connection.send("OnLocationChanging",e,t,n,o)}sendJsDataStream(e,t,n){return function(e,t,n,o){setTimeout((async()=>{let r=5,s=(new Date).valueOf();try{const i=t instanceof Blob?t.size:t.byteLength;let a=0,c=0;for(;a1)await e.send("ReceiveJSDataChunk",n,c,h,null);else{if(!await e.invoke("ReceiveJSDataChunk",n,c,h,null))break;const t=(new Date).valueOf(),o=t-s;s=t,r=Math.max(1,Math.round(500/Math.max(1,o)))}a+=l,c++}}catch(t){await e.send("ReceiveJSDataChunk",n,-1,null,t.toString())}}),0)}(this._connection,e,t,n)}resolveElement(e,t){const n=function(e){const t=f.get(e);if(t)return f.delete(e),t}(e);if(n)return O(n,!0);const o=Number.parseInt(e);if(!Number.isNaN(o))return function(e){const{start:t,end:n}=e,o=t[$];if(o){if(o!==e)throw new Error("The start component comment was already associated with another component descriptor.");return t}const r=t.parentNode;if(!r)throw new Error(`Comment not connected to the DOM ${t.textContent}`);const s=O(r,!0),i=K(s);t[L]=s,t[$]=e;const a=O(t);if(n){const e=K(a),o=Array.prototype.indexOf.call(i,a)+1;let r=null;for(;r!==n;){const n=i.splice(o,1)[0];if(!n)throw new Error("Could not find the end component comment in the parent logical node list");n[L]=t,e.push(n),r=n}}return a}(this._componentManager.resolveRootComponent(o,t));throw new Error(`Invalid sequence number or identifier '${e}'.`)}getRootComponentManager(){return this._componentManager}unhandledError(e){this._logger.log(vt.Error,e),this.disconnect()}getDisconnectFormData(){const e=new FormData,t=this._circuitId;return e.append("circuitId",t),e}didRenderingFail(){return this._renderingFailed}isDisposedOrDisposing(){return void 0!==this._disposePromise}sendDisconnectBeacon(){if(this._disposed)return;const e=this.getDisconnectFormData();this._disposed=navigator.sendBeacon("_blazor/disconnect",e)}dispose(){return this._disposePromise||(this._disposePromise=this.disposeCore()),this._disposePromise}async disposeCore(){var e;if(!this._startPromise)return void(this._disposed=!0);await this._startPromise,this._disposed=!0,null===(e=this._connection)||void 0===e||e.stop();const t=this.getDisconnectFormData();fetch("_blazor/disconnect",{method:"POST",body:t}),function(e){if(!S.delete(e))throw new Error(`Interop methods are not registered for renderer ${e}`)}(mn.Server)}}const yo={configureSignalR:e=>{},logLevel:ot.Warning,reconnectionOptions:{maxRetries:8,retryIntervalMilliseconds:2e4,dialogId:"components-reconnect-modal"}};class wo{constructor(e,t,n,o){this.maxRetries=t,this.document=n,this.logger=o,this.addedToDom=!1,this.modal=this.document.createElement("div"),this.modal.id=e,this.maxRetries=t,this.modal.style.cssText=["position: fixed","top: 0","right: 0","bottom: 0","left: 0","z-index: 1050","display: none","overflow: hidden","background-color: #fff","opacity: 0.8","text-align: center","font-weight: bold","transition: visibility 0s linear 500ms"].join(";"),this.message=this.document.createElement("h5"),this.message.style.cssText="margin-top: 20px",this.button=this.document.createElement("button"),this.button.style.cssText="margin:5px auto 5px",this.button.textContent="Retry";const r=this.document.createElement("a");r.addEventListener("click",(()=>location.reload())),r.textContent="reload",this.reloadParagraph=this.document.createElement("p"),this.reloadParagraph.textContent="Alternatively, ",this.reloadParagraph.appendChild(r),this.modal.appendChild(this.message),this.modal.appendChild(this.button),this.modal.appendChild(this.reloadParagraph),this.loader=this.getLoader(),this.message.after(this.loader),this.button.addEventListener("click",(async()=>{this.show();try{await nt.reconnect()||this.rejected()}catch(e){this.logger.log(ot.Error,e),this.failed()}}))}show(){this.addedToDom||(this.addedToDom=!0,this.document.body.appendChild(this.modal)),this.modal.style.display="block",this.loader.style.display="inline-block",this.button.style.display="none",this.reloadParagraph.style.display="none",this.message.textContent="Attempting to reconnect to the server...",this.modal.style.visibility="hidden",setTimeout((()=>{this.modal.style.visibility="visible"}),0)}update(e){this.message.textContent=`Attempting to reconnect to the server: ${e} of ${this.maxRetries}`}hide(){this.modal.style.display="none"}failed(){this.button.style.display="block",this.reloadParagraph.style.display="none",this.loader.style.display="none";const e=this.document.createTextNode("Reconnection failed. Try "),t=this.document.createElement("a");t.textContent="reloading",t.setAttribute("href",""),t.addEventListener("click",(()=>location.reload()));const n=this.document.createTextNode(" the page if you're unable to reconnect.");this.message.replaceChildren(e,t,n)}rejected(){this.button.style.display="none",this.reloadParagraph.style.display="none",this.loader.style.display="none";const e=this.document.createTextNode("Could not reconnect to the server. "),t=this.document.createElement("a");t.textContent="Reload",t.setAttribute("href",""),t.addEventListener("click",(()=>location.reload()));const n=this.document.createTextNode(" the page to restore functionality.");this.message.replaceChildren(e,t,n)}getLoader(){const e=this.document.createElement("div");return e.style.cssText=["border: 0.3em solid #f3f3f3","border-top: 0.3em solid #3498db","border-radius: 50%","width: 2em","height: 2em","display: inline-block"].join(";"),e.animate([{transform:"rotate(0deg)"},{transform:"rotate(360deg)"}],{duration:2e3,iterations:1/0}),e}}class _o{constructor(e,t,n){this.dialog=e,this.maxRetries=t,this.document=n,this.document=n;const o=this.document.getElementById(_o.MaxRetriesId);o&&(o.innerText=this.maxRetries.toString())}show(){this.removeClasses(),this.dialog.classList.add(_o.ShowClassName)}update(e){const t=this.document.getElementById(_o.CurrentAttemptId);t&&(t.innerText=e.toString())}hide(){this.removeClasses(),this.dialog.classList.add(_o.HideClassName)}failed(){this.removeClasses(),this.dialog.classList.add(_o.FailedClassName)}rejected(){this.removeClasses(),this.dialog.classList.add(_o.RejectedClassName)}removeClasses(){this.dialog.classList.remove(_o.ShowClassName,_o.HideClassName,_o.FailedClassName,_o.RejectedClassName)}}_o.ShowClassName="components-reconnect-show",_o.HideClassName="components-reconnect-hide",_o.FailedClassName="components-reconnect-failed",_o.RejectedClassName="components-reconnect-rejected",_o.MaxRetriesId="components-reconnect-max-retries",_o.CurrentAttemptId="components-reconnect-current-attempt";class bo{constructor(e,t,n){this._currentReconnectionProcess=null,this._logger=e,this._reconnectionDisplay=t,this._reconnectCallback=n||nt.reconnect}onConnectionDown(e,t){if(!this._reconnectionDisplay){const t=document.getElementById(e.dialogId);this._reconnectionDisplay=t?new _o(t,e.maxRetries,document):new wo(e.dialogId,e.maxRetries,document,this._logger)}this._currentReconnectionProcess||(this._currentReconnectionProcess=new So(e,this._logger,this._reconnectCallback,this._reconnectionDisplay))}onConnectionUp(){this._currentReconnectionProcess&&(this._currentReconnectionProcess.dispose(),this._currentReconnectionProcess=null)}}class So{constructor(e,t,n,o){this.logger=t,this.reconnectCallback=n,this.isDisposed=!1,this.reconnectDisplay=o,this.reconnectDisplay.show(),this.attemptPeriodicReconnection(e)}dispose(){this.isDisposed=!0,this.reconnectDisplay.hide()}async attemptPeriodicReconnection(e){for(let t=0;tSo.MaximumFirstRetryInterval?So.MaximumFirstRetryInterval:e.retryIntervalMilliseconds;if(await this.delay(n),this.isDisposed)break;try{return await this.reconnectCallback()?void 0:void this.reconnectDisplay.rejected()}catch(e){this.logger.log(ot.Error,e)}}this.reconnectDisplay.failed()}delay(e){return new Promise((t=>setTimeout(t,e)))}}So.MaximumFirstRetryInterval=3e3;class Eo{constructor(){this.afterStartedCallbacks=[]}async importInitializersAsync(e,t){await Promise.all(e.map((e=>async function(e,n){const o=function(e){const t=document.baseURI;return t.endsWith("/")?`${t}${e}`:`${t}/${e}`}(n),r=await import(o);if(void 0===r)return;const{beforeStart:s,afterStarted:i}=r;return i&&e.afterStartedCallbacks.push(i),s?s(...t):void 0}(this,e))))}async invokeAfterStartedCallbacks(e){await I,await Promise.all(this.afterStartedCallbacks.map((t=>t(e))))}}let Co,Io,ko,To,Do=!1;async function xo(e){if(Do)throw new Error("Blazor Server has already started.");var t;Do=!0,t=document,Co=at(t,it)||"",To=new st(ko.logLevel),Io=new vo(e,Co,ko,To),To.log(ot.Information,"Starting up Blazor server-side application."),nt.reconnect=async()=>!(Io.didRenderingFail()||!await Io.reconnect()&&(To.log(ot.Information,"Reconnection attempt to the circuit was rejected by the server. This may indicate that the associated state is no longer available on the server."),1)),nt.defaultReconnectionHandler=new bo(To),ko.reconnectionHandler=ko.reconnectionHandler||nt.defaultReconnectionHandler,nt._internal.navigationManager.listenForNavigationEvents(((e,t,n)=>Io.sendLocationChanged(e,t,n)),((e,t,n,o)=>Io.sendLocationChanging(e,t,n,o))),nt._internal.forceCloseConnection=()=>Io.disconnect(),nt._internal.sendJSDataStream=(e,t,n)=>Io.sendJsDataStream(e,t,n);const n=await async function(e){const t=await fetch("_blazor/initializers",{method:"GET",credentials:"include",cache:"no-cache"}),n=await t.json(),o=new Eo;return await o.importInitializersAsync(n,[e]),o}(ko);if(!await Io.start())return void To.log(ot.Error,"Failed to start the circuit.");const o=()=>{Io.sendDisconnectBeacon()};nt.disconnect=o,window.addEventListener("unload",o,{capture:!1,once:!0}),To.log(ot.Information,"Blazor server-side application started."),n.invokeAfterStartedCallbacks(nt)}class Ro{constructor(e){this.initialComponents=e}resolveRootComponent(e,t){return this.initialComponents[e]}}class Po{constructor(){this._eventListeners=new Map}static create(e){const t=new Po;return e.addEventListener=t.addEventListener.bind(t),e.removeEventListener=t.removeEventListener.bind(t),t}addEventListener(e,t){let n=this._eventListeners.get(e);n||(n=new Set,this._eventListeners.set(e,n)),n.add(t)}removeEventListener(e,t){var n;null===(n=this._eventListeners.get(e))||void 0===n||n.delete(t)}dispatchEvent(e,t){const n=this._eventListeners.get(e);if(!n)return;const o={...t,type:e};for(const e of n)e(o)}}let Ao=!1;function No(e){if(Ao)throw new Error("Blazor has already started.");Ao=!0,function(e){if(ko)throw new Error("Circuit options have already been configured.");ko=function(e){const t={...yo,...e};return e&&e.reconnectionOptions&&(t.reconnectionOptions={...yo.reconnectionOptions,...e.reconnectionOptions}),t}(e)}(e),Po.create(nt);const t=function(e){return ct(e,"server").sort(((e,t)=>e.sequence-t.sequence))}(document);return xo(new Ro(t))}nt.start=No,window.DotNet=e,document&&document.currentScript&&"false"!==document.currentScript.getAttribute("autostart")&&No()})()})(); \ No newline at end of file diff --git a/src/Components/Web.JS/dist/Release/blazor.web.js b/src/Components/Web.JS/dist/Release/blazor.web.js index 971a29f6df72..068d2dee76cf 100644 --- a/src/Components/Web.JS/dist/Release/blazor.web.js +++ b/src/Components/Web.JS/dist/Release/blazor.web.js @@ -1 +1 @@ -(()=>{var e={778:()=>{},77:()=>{},203:()=>{},200:()=>{},628:()=>{},321:()=>{}},t={};function n(o){var r=t[o];if(void 0!==r)return r.exports;var i=t[o]={exports:{}};return e[o](i,i.exports,n),i.exports}n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),(()=>{"use strict";var e,t,o;!function(e){const t=[],n="__jsObjectId",o="__dotNetObject",r="__byte[]",i="__dotNetStream",s="__jsStreamReferenceLength";let a,c;class l{constructor(e){this._jsObject=e,this._cachedFunctions=new Map}findFunction(e){const t=this._cachedFunctions.get(e);if(t)return t;let n,o=this._jsObject;if(e.split(".").forEach((t=>{if(!(t in o))throw new Error(`Could not find '${e}' ('${t}' was undefined).`);n=o,o=o[t]})),o instanceof Function)return o=o.bind(n),this._cachedFunctions.set(e,o),o;throw new Error(`The value '${e}' is not a function.`)}getWrappedObject(){return this._jsObject}}const h={0:new l(window)};h[0]._cachedFunctions.set("import",(e=>("string"==typeof e&&e.startsWith("./")&&(e=new URL(e.substr(2),document.baseURI).toString()),import(e))));let d,u=1;function p(e){t.push(e)}function f(e){if(e&&"object"==typeof e){h[u]=new l(e);const t={[n]:u};return u++,t}throw new Error(`Cannot create a JSObjectReference from the value '${e}'.`)}function g(e){let t=-1;if(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),e instanceof Blob)t=e.size;else{if(!(e.buffer instanceof ArrayBuffer))throw new Error("Supplied value is not a typed array or blob.");if(void 0===e.byteLength)throw new Error(`Cannot create a JSStreamReference from the value '${e}' as it doesn't have a byteLength.`);t=e.byteLength}const o={[s]:t};try{const t=f(e);o[n]=t[n]}catch(t){throw new Error(`Cannot create a JSStreamReference from the value '${e}'.`)}return o}function m(e,n){c=e;const o=n?JSON.parse(n,((e,n)=>t.reduce(((t,n)=>n(e,t)),n))):null;return c=void 0,o}function y(){if(void 0===a)throw new Error("No call dispatcher has been set.");if(null===a)throw new Error("There are multiple .NET runtimes present, so a default dispatcher could not be resolved. Use DotNetObject to invoke .NET instance methods.");return a}e.attachDispatcher=function(e){const t=new v(e);return void 0===a?a=t:a&&(a=null),t},e.attachReviver=p,e.invokeMethod=function(e,t,...n){return y().invokeDotNetStaticMethod(e,t,...n)},e.invokeMethodAsync=function(e,t,...n){return y().invokeDotNetStaticMethodAsync(e,t,...n)},e.createJSObjectReference=f,e.createJSStreamReference=g,e.disposeJSObjectReference=function(e){const t=e&&e[n];"number"==typeof t&&_(t)},function(e){e[e.Default=0]="Default",e[e.JSObjectReference=1]="JSObjectReference",e[e.JSStreamReference=2]="JSStreamReference",e[e.JSVoidResult=3]="JSVoidResult"}(d=e.JSCallResultType||(e.JSCallResultType={}));class v{constructor(e){this._dotNetCallDispatcher=e,this._byteArraysToBeRevived=new Map,this._pendingDotNetToJSStreams=new Map,this._pendingAsyncCalls={},this._nextAsyncCallId=1}getDotNetCallDispatcher(){return this._dotNetCallDispatcher}invokeJSFromDotNet(e,t,n,o){const r=m(this,t),i=I(b(e,o)(...r||[]),n);return null==i?null:T(this,i)}beginInvokeJSFromDotNet(e,t,n,o,r){const i=new Promise((e=>{const o=m(this,n);e(b(t,r)(...o||[]))}));e&&i.then((t=>T(this,[e,!0,I(t,o)]))).then((t=>this._dotNetCallDispatcher.endInvokeJSFromDotNet(e,!0,t)),(t=>this._dotNetCallDispatcher.endInvokeJSFromDotNet(e,!1,JSON.stringify([e,!1,w(t)]))))}endInvokeDotNetFromJS(e,t,n){const o=t?m(this,n):new Error(n);this.completePendingCall(parseInt(e,10),t,o)}invokeDotNetStaticMethod(e,t,...n){return this.invokeDotNetMethod(e,t,null,n)}invokeDotNetStaticMethodAsync(e,t,...n){return this.invokeDotNetMethodAsync(e,t,null,n)}invokeDotNetMethod(e,t,n,o){if(this._dotNetCallDispatcher.invokeDotNetFromJS){const r=T(this,o),i=this._dotNetCallDispatcher.invokeDotNetFromJS(e,t,n,r);return i?m(this,i):null}throw new Error("The current dispatcher does not support synchronous calls from JS to .NET. Use invokeDotNetMethodAsync instead.")}invokeDotNetMethodAsync(e,t,n,o){if(e&&n)throw new Error(`For instance method calls, assemblyName should be null. Received '${e}'.`);const r=this._nextAsyncCallId++,i=new Promise(((e,t)=>{this._pendingAsyncCalls[r]={resolve:e,reject:t}}));try{const i=T(this,o);this._dotNetCallDispatcher.beginInvokeDotNetFromJS(r,e,t,n,i)}catch(e){this.completePendingCall(r,!1,e)}return i}receiveByteArray(e,t){this._byteArraysToBeRevived.set(e,t)}processByteArray(e){const t=this._byteArraysToBeRevived.get(e);return t?(this._byteArraysToBeRevived.delete(e),t):null}supplyDotNetStream(e,t){if(this._pendingDotNetToJSStreams.has(e)){const n=this._pendingDotNetToJSStreams.get(e);this._pendingDotNetToJSStreams.delete(e),n.resolve(t)}else{const n=new C;n.resolve(t),this._pendingDotNetToJSStreams.set(e,n)}}getDotNetStreamPromise(e){let t;if(this._pendingDotNetToJSStreams.has(e))t=this._pendingDotNetToJSStreams.get(e).streamPromise,this._pendingDotNetToJSStreams.delete(e);else{const n=new C;this._pendingDotNetToJSStreams.set(e,n),t=n.streamPromise}return t}completePendingCall(e,t,n){if(!this._pendingAsyncCalls.hasOwnProperty(e))throw new Error(`There is no pending async call with ID ${e}.`);const o=this._pendingAsyncCalls[e];delete this._pendingAsyncCalls[e],t?o.resolve(n):o.reject(n)}}function w(e){return e instanceof Error?`${e.message}\n${e.stack}`:e?e.toString():"null"}function b(e,t){const n=h[t];if(n)return n.findFunction(e);throw new Error(`JS object instance with ID ${t} does not exist (has it been disposed?).`)}function _(e){delete h[e]}e.findJSFunction=b,e.disposeJSObjectReferenceById=_;class E{constructor(e,t){this._id=e,this._callDispatcher=t}invokeMethod(e,...t){return this._callDispatcher.invokeDotNetMethod(null,e,this._id,t)}invokeMethodAsync(e,...t){return this._callDispatcher.invokeDotNetMethodAsync(null,e,this._id,t)}dispose(){this._callDispatcher.invokeDotNetMethodAsync(null,"__Dispose",this._id,null).catch((e=>console.error(e)))}serializeAsArg(){return{[o]:this._id}}}e.DotNetObject=E,p((function(e,t){if(t&&"object"==typeof t){if(t.hasOwnProperty(o))return new E(t[o],c);if(t.hasOwnProperty(n)){const e=t[n],o=h[e];if(o)return o.getWrappedObject();throw new Error(`JS object instance with Id '${e}' does not exist. It may have been disposed.`)}if(t.hasOwnProperty(r)){const e=t[r],n=c.processByteArray(e);if(void 0===n)throw new Error(`Byte array index '${e}' does not exist.`);return n}if(t.hasOwnProperty(i)){const e=t[i],n=c.getDotNetStreamPromise(e);return new S(n)}}return t}));class S{constructor(e){this._streamPromise=e}stream(){return this._streamPromise}async arrayBuffer(){return new Response(await this.stream()).arrayBuffer()}}class C{constructor(){this.streamPromise=new Promise(((e,t)=>{this.resolve=e,this.reject=t}))}}function I(e,t){switch(t){case d.Default:return e;case d.JSObjectReference:return f(e);case d.JSStreamReference:return g(e);case d.JSVoidResult:return null;default:throw new Error(`Invalid JS call result type '${t}'.`)}}let k=0;function T(e,t){k=0,c=e;const n=JSON.stringify(t,D);return c=void 0,n}function D(e,t){if(t instanceof E)return t.serializeAsArg();if(t instanceof Uint8Array){c.getDotNetCallDispatcher().sendByteArray(k,t);const e={[r]:k};return k++,e}return t}}(e||(e={})),function(e){e[e.prependFrame=1]="prependFrame",e[e.removeFrame=2]="removeFrame",e[e.setAttribute=3]="setAttribute",e[e.removeAttribute=4]="removeAttribute",e[e.updateText=5]="updateText",e[e.stepIn=6]="stepIn",e[e.stepOut=7]="stepOut",e[e.updateMarkup=8]="updateMarkup",e[e.permutationListEntry=9]="permutationListEntry",e[e.permutationListEnd=10]="permutationListEnd"}(t||(t={})),function(e){e[e.element=1]="element",e[e.text=2]="text",e[e.attribute=3]="attribute",e[e.component=4]="component",e[e.region=5]="region",e[e.elementReferenceCapture=6]="elementReferenceCapture",e[e.markup=8]="markup",e[e.namedEvent=10]="namedEvent"}(o||(o={}));class r{constructor(e,t){this.componentId=e,this.fieldValue=t}static fromEvent(e,t){const n=t.target;if(n instanceof Element){const t=function(e){return e instanceof HTMLInputElement?e.type&&"checkbox"===e.type.toLowerCase()?{value:e.checked}:{value:e.value}:e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement?{value:e.value}:null}(n);if(t)return new r(e,t.value)}return null}}const i=new Map,s=new Map,a=[];function c(e){return i.get(e)}function l(e){const t=i.get(e);return(null==t?void 0:t.browserEventName)||e}function h(e,t){e.forEach((e=>i.set(e,t)))}function d(e){const t=[];for(let n=0;ne.selected)).map((e=>e.value))}}{const e=function(e){return!!e&&"INPUT"===e.tagName&&"checkbox"===e.getAttribute("type")}(t);return{value:e?!!t.checked:t.value}}}}),h(["copy","cut","paste"],{createEventArgs:e=>({type:e.type})}),h(["drag","dragend","dragenter","dragleave","dragover","dragstart","drop"],{createEventArgs:e=>{return{...u(t=e),dataTransfer:t.dataTransfer?{dropEffect:t.dataTransfer.dropEffect,effectAllowed:t.dataTransfer.effectAllowed,files:Array.from(t.dataTransfer.files).map((e=>e.name)),items:Array.from(t.dataTransfer.items).map((e=>({kind:e.kind,type:e.type}))),types:t.dataTransfer.types}:null};var t}}),h(["focus","blur","focusin","focusout"],{createEventArgs:e=>({type:e.type})}),h(["keydown","keyup","keypress"],{createEventArgs:e=>{return{key:(t=e).key,code:t.code,location:t.location,repeat:t.repeat,ctrlKey:t.ctrlKey,shiftKey:t.shiftKey,altKey:t.altKey,metaKey:t.metaKey,type:t.type};var t}}),h(["contextmenu","click","mouseover","mouseout","mousemove","mousedown","mouseup","mouseleave","mouseenter","dblclick"],{createEventArgs:e=>u(e)}),h(["error"],{createEventArgs:e=>{return{message:(t=e).message,filename:t.filename,lineno:t.lineno,colno:t.colno,type:t.type};var t}}),h(["loadstart","timeout","abort","load","loadend","progress"],{createEventArgs:e=>{return{lengthComputable:(t=e).lengthComputable,loaded:t.loaded,total:t.total,type:t.type};var t}}),h(["touchcancel","touchend","touchmove","touchenter","touchleave","touchstart"],{createEventArgs:e=>{return{detail:(t=e).detail,touches:d(t.touches),targetTouches:d(t.targetTouches),changedTouches:d(t.changedTouches),ctrlKey:t.ctrlKey,shiftKey:t.shiftKey,altKey:t.altKey,metaKey:t.metaKey,type:t.type};var t}}),h(["gotpointercapture","lostpointercapture","pointercancel","pointerdown","pointerenter","pointerleave","pointermove","pointerout","pointerover","pointerup"],{createEventArgs:e=>{return{...u(t=e),pointerId:t.pointerId,width:t.width,height:t.height,pressure:t.pressure,tiltX:t.tiltX,tiltY:t.tiltY,pointerType:t.pointerType,isPrimary:t.isPrimary};var t}}),h(["wheel","mousewheel"],{createEventArgs:e=>{return{...u(t=e),deltaX:t.deltaX,deltaY:t.deltaY,deltaZ:t.deltaZ,deltaMode:t.deltaMode};var t}}),h(["cancel","close","toggle"],{createEventArgs:()=>({})});const p=["date","datetime-local","month","time","week"],f=new Map;let g,m,y=0;const v={async add(e,t,n){if(!n)throw new Error("initialParameters must be an object, even if empty.");const o="__bl-dynamic-root:"+(++y).toString();f.set(o,e);const r=await E().invokeMethodAsync("AddRootComponent",t,o),i=new _(r,m[t]);return await i.setParameters(n),i}};function w(e){const t=f.get(e);if(t)return f.delete(e),t}class b{invoke(e){return this._callback(e)}setCallback(t){this._selfJSObjectReference||(this._selfJSObjectReference=e.createJSObjectReference(this)),this._callback=t}getJSObjectReference(){return this._selfJSObjectReference}dispose(){this._selfJSObjectReference&&e.disposeJSObjectReference(this._selfJSObjectReference)}}class _{constructor(e,t){this._jsEventCallbackWrappers=new Map,this._componentId=e;for(const e of t)"eventcallback"===e.type&&this._jsEventCallbackWrappers.set(e.name.toLowerCase(),new b)}setParameters(e){const t={},n=Object.entries(e||{}),o=n.length;for(const[e,o]of n){const n=this._jsEventCallbackWrappers.get(e.toLowerCase());n&&o?(n.setCallback(o),t[e]=n.getJSObjectReference()):t[e]=o}return E().invokeMethodAsync("SetRootComponentParameters",this._componentId,o,t)}async dispose(){if(null!==this._componentId){await E().invokeMethodAsync("RemoveRootComponent",this._componentId),this._componentId=null;for(const e of this._jsEventCallbackWrappers.values())e.dispose()}}}function E(){if(!g)throw new Error("Dynamic root components have not been enabled in this application.");return g}const S=new Map,C=[];let I;const k=new Promise((e=>{I=e}));function T(e,t,n){return R(e,t.eventHandlerId,(()=>D(e).invokeMethodAsync("DispatchEventAsync",t,n)))}function D(e){const t=S.get(e);if(!t)throw new Error(`No interop methods are registered for renderer ${e}`);return t}let R=(e,t,n)=>n();const x=L(["abort","blur","cancel","canplay","canplaythrough","change","close","cuechange","durationchange","emptied","ended","error","focus","load","loadeddata","loadedmetadata","loadend","loadstart","mouseenter","mouseleave","pointerenter","pointerleave","pause","play","playing","progress","ratechange","reset","scroll","seeked","seeking","stalled","submit","suspend","timeupdate","toggle","unload","volumechange","waiting","DOMNodeInsertedIntoDocument","DOMNodeRemovedFromDocument"]),A={submit:!0},N=L(["click","dblclick","mousedown","mousemove","mouseup"]);class M{constructor(e){this.browserRendererId=e,this.afterClickCallbacks=[];const t=++M.nextEventDelegatorId;this.eventsCollectionKey=`_blazorEvents_${t}`,this.eventInfoStore=new P(this.onGlobalEvent.bind(this))}setListener(e,t,n,o){const r=this.getEventHandlerInfosForElement(e,!0),i=r.getHandler(t);if(i)this.eventInfoStore.update(i.eventHandlerId,n);else{const i={element:e,eventName:t,eventHandlerId:n,renderingComponentId:o};this.eventInfoStore.add(i),r.setHandler(t,i)}}getHandler(e){return this.eventInfoStore.get(e)}removeListener(e){const t=this.eventInfoStore.remove(e);if(t){const e=t.element,n=this.getEventHandlerInfosForElement(e,!1);n&&n.removeHandler(t.eventName)}}notifyAfterClick(e){this.afterClickCallbacks.push(e),this.eventInfoStore.addGlobalListener("click")}setStopPropagation(e,t,n){this.getEventHandlerInfosForElement(e,!0).stopPropagation(t,n)}setPreventDefault(e,t,n){this.getEventHandlerInfosForElement(e,!0).preventDefault(t,n)}onGlobalEvent(e){if(!(e.target instanceof Element))return;this.dispatchGlobalEventToAllElements(e.type,e);const t=(n=e.type,s.get(n));var n;t&&t.forEach((t=>this.dispatchGlobalEventToAllElements(t,e))),"click"===e.type&&this.afterClickCallbacks.forEach((t=>t(e)))}dispatchGlobalEventToAllElements(e,t){const n=t.composedPath();let o=n.shift(),i=null,s=!1;const a=Object.prototype.hasOwnProperty.call(x,e);let l=!1;for(;o;){const u=o,p=this.getEventHandlerInfosForElement(u,!1);if(p){const n=p.getHandler(e);if(n&&(h=u,d=t.type,!((h instanceof HTMLButtonElement||h instanceof HTMLInputElement||h instanceof HTMLTextAreaElement||h instanceof HTMLSelectElement)&&Object.prototype.hasOwnProperty.call(N,d)&&h.disabled))){if(!s){const n=c(e);i=(null==n?void 0:n.createEventArgs)?n.createEventArgs(t):{},s=!0}Object.prototype.hasOwnProperty.call(A,t.type)&&t.preventDefault(),T(this.browserRendererId,{eventHandlerId:n.eventHandlerId,eventName:e,eventFieldInfo:r.fromEvent(n.renderingComponentId,t)},i)}p.stopPropagation(e)&&(l=!0),p.preventDefault(e)&&t.preventDefault()}o=a||l?void 0:n.shift()}var h,d}getEventHandlerInfosForElement(e,t){return Object.prototype.hasOwnProperty.call(e,this.eventsCollectionKey)?e[this.eventsCollectionKey]:t?e[this.eventsCollectionKey]=new U:null}}M.nextEventDelegatorId=0;class P{constructor(e){this.globalListener=e,this.infosByEventHandlerId={},this.countByEventName={},a.push(this.handleEventNameAliasAdded.bind(this))}add(e){if(this.infosByEventHandlerId[e.eventHandlerId])throw new Error(`Event ${e.eventHandlerId} is already tracked`);this.infosByEventHandlerId[e.eventHandlerId]=e,this.addGlobalListener(e.eventName)}get(e){return this.infosByEventHandlerId[e]}addGlobalListener(e){if(e=l(e),Object.prototype.hasOwnProperty.call(this.countByEventName,e))this.countByEventName[e]++;else{this.countByEventName[e]=1;const t=Object.prototype.hasOwnProperty.call(x,e);document.addEventListener(e,this.globalListener,t)}}update(e,t){if(Object.prototype.hasOwnProperty.call(this.infosByEventHandlerId,t))throw new Error(`Event ${t} is already tracked`);const n=this.infosByEventHandlerId[e];delete this.infosByEventHandlerId[e],n.eventHandlerId=t,this.infosByEventHandlerId[t]=n}remove(e){const t=this.infosByEventHandlerId[e];if(t){delete this.infosByEventHandlerId[e];const n=l(t.eventName);0==--this.countByEventName[n]&&(delete this.countByEventName[n],document.removeEventListener(n,this.globalListener))}return t}handleEventNameAliasAdded(e,t){if(Object.prototype.hasOwnProperty.call(this.countByEventName,e)){const n=this.countByEventName[e];delete this.countByEventName[e],document.removeEventListener(e,this.globalListener),this.addGlobalListener(t),this.countByEventName[t]+=n-1}}}class U{constructor(){this.handlers={},this.preventDefaultFlags=null,this.stopPropagationFlags=null}getHandler(e){return Object.prototype.hasOwnProperty.call(this.handlers,e)?this.handlers[e]:null}setHandler(e,t){this.handlers[e]=t}removeHandler(e){delete this.handlers[e]}preventDefault(e,t){return void 0!==t&&(this.preventDefaultFlags=this.preventDefaultFlags||{},this.preventDefaultFlags[e]=t),!!this.preventDefaultFlags&&this.preventDefaultFlags[e]}stopPropagation(e,t){return void 0!==t&&(this.stopPropagationFlags=this.stopPropagationFlags||{},this.stopPropagationFlags[e]=t),!!this.stopPropagationFlags&&this.stopPropagationFlags[e]}}function L(e){const t={};return e.forEach((e=>{t[e]=!0})),t}const B=Symbol(),F=Symbol(),O=Symbol();function $(e){const{start:t,end:n}=e,o=t[O];if(o){if(o!==e)throw new Error("The start component comment was already associated with another component descriptor.");return t}const r=t.parentNode;if(!r)throw new Error(`Comment not connected to the DOM ${t.textContent}`);const i=H(r,!0),s=G(i);t[F]=i,t[O]=e;const a=H(t);if(n){const e=G(a),o=Array.prototype.indexOf.call(s,a)+1;let r=null;for(;r!==n;){const n=s.splice(o,1)[0];if(!n)throw new Error("Could not find the end component comment in the parent logical node list");n[F]=t,e.push(n),r=n}}return a}function H(e,t){if(B in e)return e;const n=[];if(e.childNodes.length>0){if(!t)throw new Error("New logical elements must start empty, or allowExistingContents must be true");e.childNodes.forEach((t=>{const o=H(t,!0);o[F]=e,n.push(o)}))}return e[B]=n,e}function j(e){const t=G(e);for(;t.length;)z(e,0)}function W(e,t){const n=document.createComment("!");return q(n,e,t),n}function q(e,t,n){const o=e;let r=e;if(Q(e)){const t=ne(o);if(t!==e){const n=new Range;n.setStartBefore(e),n.setEndAfter(t),r=n.extractContents()}}const i=J(o);if(i){const e=G(i),t=Array.prototype.indexOf.call(e,o);e.splice(t,1),delete o[F]}const s=G(t);if(n0;)z(n,0)}const o=n;o.parentNode.removeChild(o)}function J(e){return e[F]||null}function K(e,t){return G(e)[t]}function V(e){return e[O]||null}function X(e){const t=ee(e);return"http://www.w3.org/2000/svg"===t.namespaceURI&&"foreignObject"!==t.tagName}function G(e){return e[B]}function Y(e){const t=G(J(e));return t[Array.prototype.indexOf.call(t,e)+1]||null}function Q(e){return B in e}function Z(e,t){const n=G(e);t.forEach((e=>{e.moveRangeStart=n[e.fromSiblingIndex],e.moveRangeEnd=ne(e.moveRangeStart)})),t.forEach((t=>{const o=document.createComment("marker");t.moveToBeforeMarker=o;const r=n[t.toSiblingIndex+1];r?r.parentNode.insertBefore(o,r):te(o,e)})),t.forEach((e=>{const t=e.moveToBeforeMarker,n=t.parentNode,o=e.moveRangeStart,r=e.moveRangeEnd;let i=o;for(;i;){const e=i.nextSibling;if(n.insertBefore(i,t),i===r)break;i=e}n.removeChild(t)})),t.forEach((e=>{n[e.toSiblingIndex]=e.moveRangeStart}))}function ee(e){if(e instanceof Element||e instanceof DocumentFragment)return e;if(e instanceof Comment)return e.parentNode;throw new Error("Not a valid logical element")}function te(e,t){if(t instanceof Element||t instanceof DocumentFragment)t.appendChild(e);else{if(!(t instanceof Comment))throw new Error(`Cannot append node because the parent is not a valid logical element. Parent: ${t}`);{const n=Y(t);n?n.parentNode.insertBefore(e,n):te(e,J(t))}}}function ne(e){if(e instanceof Element||e instanceof DocumentFragment)return e;const t=Y(e);if(t)return t.previousSibling;{const t=J(e);return t instanceof Element||t instanceof DocumentFragment?t.lastChild:ne(t)}}function oe(e){return`_bl_${e}`}const re="__internalId";e.attachReviver(((e,t)=>t&&"object"==typeof t&&Object.prototype.hasOwnProperty.call(t,re)&&"string"==typeof t[re]?function(e){const t=`[${oe(e)}]`;return document.querySelector(t)}(t[re]):t));const ie="_blazorDeferredValue";function se(e){e instanceof HTMLOptionElement?he(e):ie in e&&le(e,e[ie])}function ae(e){return"select-multiple"===e.type}function ce(e,t){e.value=t||""}function le(e,t){e instanceof HTMLSelectElement?ae(e)?function(e,t){t||(t=[]);for(let n=0;n{Pe()&&De(e,(e=>{Je(e,!0,!1)}))}))}getRootComponentCount(){return this.rootComponentIds.size}attachRootComponentToLogicalElement(e,t,n){if(ye(t))throw new Error(`Root component '${e}' could not be attached because its target element is already associated with a root component`);me(t,!0),this.attachComponentToElement(e,t),this.rootComponentIds.add(e),n||(pe[e]=t)}updateComponent(e,t,n,o){var r;const i=this.childComponentLocations[t];if(!i)throw new Error(`No element is currently associated with component ${t}`);const s=pe[t];s&&(delete pe[t],j(s),s instanceof Comment&&(s.textContent="!"));const a=null===(r=ee(i))||void 0===r?void 0:r.getRootNode(),c=a&&a.activeElement;this.applyEdits(e,t,i,0,n,o),c instanceof HTMLElement&&a&&a.activeElement!==c&&c.focus()}disposeComponent(e){if(this.rootComponentIds.delete(e)){const t=this.childComponentLocations[e];me(t,!1),j(t)}delete this.childComponentLocations[e]}disposeEventHandler(e){this.eventDelegator.removeListener(e)}attachComponentToElement(e,t){this.childComponentLocations[e]=t}applyEdits(e,n,o,r,i,s){let a,c=0,l=r;const h=e.arrayBuilderSegmentReader,d=e.editReader,u=e.frameReader,p=h.values(i),f=h.offset(i),g=f+h.count(i);for(let i=f;idocument.baseURI,getLocationHref:()=>location.href,scrollToElement:qe};function qe(e){const t=document.getElementById(e);return!!t&&(t.scrollIntoView(),!0)}function ze(e,t,n=!1){const o=Ne(e);!t.forceLoad&&Re(o)?Ze()?Je(o,!1,t.replaceHistoryEntry,t.historyEntryState,n):Ae(o,t.replaceHistoryEntry):function(e,t){if(location.href===e){const t=e+"?";history.replaceState(null,"",t),location.replace(e)}else t?location.replace(e):location.href=e}(e,t.replaceHistoryEntry)}async function Je(e,t,n,o=void 0,r=!1){if(Xe(),function(e){const t=e.indexOf("#");return t>-1&&location.href.replace(location.hash,"")===e.substring(0,t)}(e))!function(e,t,n){Ke(e,t,n);const o=e.indexOf("#");o!==e.length-1&&qe(e.substring(o+1))}(e,n,o);else{if(!r&&Le&&!await Ge(e,o,t))return;_e=!0,Ke(e,n,o),await Ye(t)}}function Ke(e,t,n=void 0){t?history.replaceState({userState:n,_index:Be},"",e):(Be++,history.pushState({userState:n,_index:Be},"",e))}function Ve(e){return new Promise((t=>{const n=He;He=()=>{He=n,t()},history.go(e)}))}function Xe(){je&&(je(!1),je=null)}function Ge(e,t,n){return new Promise((o=>{Xe(),$e?(Fe++,je=o,$e(Fe,e,t,n)):o(!1)}))}async function Ye(e){var t;Oe&&await Oe(location.href,null===(t=history.state)||void 0===t?void 0:t.userState,e)}async function Qe(e){var t,n;He&&Ze()&&await He(e),Be=null!==(n=null===(t=history.state)||void 0===t?void 0:t._index)&&void 0!==n?n:0}function Ze(){return Pe()||!xe()}const et={focus:function(e,t){if(e instanceof HTMLElement)e.focus({preventScroll:t});else{if(!(e instanceof SVGElement))throw new Error("Unable to focus an invalid element.");if(!e.hasAttribute("tabindex"))throw new Error("Unable to focus an SVG element that does not have a tabindex.");e.focus({preventScroll:t})}},focusBySelector:function(e,t){const n=document.querySelector(e);n&&(n.hasAttribute("tabindex")||(n.tabIndex=-1),n.focus({preventScroll:!0}))}},tt={init:function(e,t,n,o=50){const r=ot(t);(r||document.documentElement).style.overflowAnchor="none";const i=document.createRange();u(n.parentElement)&&(t.style.display="table-row",n.style.display="table-row");const s=new IntersectionObserver((function(o){o.forEach((o=>{var r;if(!o.isIntersecting)return;i.setStartAfter(t),i.setEndBefore(n);const s=i.getBoundingClientRect().height,a=null===(r=o.rootBounds)||void 0===r?void 0:r.height;o.target===t?e.invokeMethodAsync("OnSpacerBeforeVisible",o.intersectionRect.top-o.boundingClientRect.top,s,a):o.target===n&&n.offsetHeight>0&&e.invokeMethodAsync("OnSpacerAfterVisible",o.boundingClientRect.bottom-o.intersectionRect.bottom,s,a)}))}),{root:r,rootMargin:`${o}px`});s.observe(t),s.observe(n);const a=d(t),c=d(n),{observersByDotNetObjectId:l,id:h}=rt(e);function d(e){const t={attributes:!0},n=new MutationObserver(((n,o)=>{u(e.parentElement)&&(o.disconnect(),e.style.display="table-row",o.observe(e,t)),s.unobserve(e),s.observe(e)}));return n.observe(e,t),n}function u(e){return null!==e&&(e instanceof HTMLTableElement&&""===e.style.display||"table"===e.style.display||e instanceof HTMLTableSectionElement&&""===e.style.display||"table-row-group"===e.style.display)}l[h]={intersectionObserver:s,mutationObserverBefore:a,mutationObserverAfter:c}},dispose:function(e){const{observersByDotNetObjectId:t,id:n}=rt(e),o=t[n];o&&(o.intersectionObserver.disconnect(),o.mutationObserverBefore.disconnect(),o.mutationObserverAfter.disconnect(),e.dispose(),delete t[n])}},nt=Symbol();function ot(e){return e&&e!==document.body&&e!==document.documentElement?"visible"!==getComputedStyle(e).overflowY?e:ot(e.parentElement):null}function rt(e){var t;const n=e._callDispatcher,o=e._id;return null!==(t=n[nt])&&void 0!==t||(n[nt]={}),{observersByDotNetObjectId:n[nt],id:o}}const it={getAndRemoveExistingTitle:function(){var e;const t=document.head?document.head.getElementsByTagName("title"):[];if(0===t.length)return null;let n=null;for(let o=t.length-1;o>=0;o--){const r=t[o],i=r.previousSibling;i instanceof Comment&&null!==J(i)||(null===n&&(n=r.textContent),null===(e=r.parentNode)||void 0===e||e.removeChild(r))}return n}},st={init:function(e,t){t._blazorInputFileNextFileId=0,t.addEventListener("click",(function(){t.value=""})),t.addEventListener("change",(function(){t._blazorFilesById={};const n=Array.prototype.map.call(t.files,(function(e){const n={id:++t._blazorInputFileNextFileId,lastModified:new Date(e.lastModified).toISOString(),name:e.name,size:e.size,contentType:e.type,readPromise:void 0,arrayBuffer:void 0,blob:e};return t._blazorFilesById[n.id]=n,n}));e.invokeMethodAsync("NotifyChange",n)}))},toImageFile:async function(e,t,n,o,r){const i=at(e,t),s=await new Promise((function(e){const t=new Image;t.onload=function(){URL.revokeObjectURL(t.src),e(t)},t.onerror=function(){t.onerror=null,URL.revokeObjectURL(t.src)},t.src=URL.createObjectURL(i.blob)})),a=await new Promise((function(e){var t;const i=Math.min(1,o/s.width),a=Math.min(1,r/s.height),c=Math.min(i,a),l=document.createElement("canvas");l.width=Math.round(s.width*c),l.height=Math.round(s.height*c),null===(t=l.getContext("2d"))||void 0===t||t.drawImage(s,0,0,l.width,l.height),l.toBlob(e,n)})),c={id:++e._blazorInputFileNextFileId,lastModified:i.lastModified,name:i.name,size:(null==a?void 0:a.size)||0,contentType:n,blob:a||i.blob};return e._blazorFilesById[c.id]=c,c},readFileData:async function(e,t){return at(e,t).blob}};function at(e,t){const n=e._blazorFilesById[t];if(!n)throw new Error(`There is no file with ID ${t}. The file list may have changed. See https://aka.ms/aspnet/blazor-input-file-multiple-selections.`);return n}const ct=new Set,lt={enableNavigationPrompt:function(e){0===ct.size&&window.addEventListener("beforeunload",ht),ct.add(e)},disableNavigationPrompt:function(e){ct.delete(e),0===ct.size&&window.removeEventListener("beforeunload",ht)}};function ht(e){e.preventDefault(),e.returnValue=!0}async function dt(e,t,n){return e instanceof Blob?await async function(e,t,n){const o=e.slice(t,t+n),r=await o.arrayBuffer();return new Uint8Array(r)}(e,t,n):function(e,t,n){return new Uint8Array(e.buffer,e.byteOffset+t,n)}(e,t,n)}const ut=new Map,pt={navigateTo:function(e,t,n=!1){ze(e,t instanceof Object?t:{forceLoad:t,replaceHistoryEntry:n})},registerCustomEventType:function(e,t){if(!t)throw new Error("The options parameter is required.");if(i.has(e))throw new Error(`The event '${e}' is already registered.`);if(t.browserEventName){const n=s.get(t.browserEventName);n?n.push(e):s.set(t.browserEventName,[e]),a.forEach((n=>n(e,t.browserEventName)))}i.set(e,t)},rootComponents:v,runtime:{},_internal:{navigationManager:We,domWrapper:et,Virtualize:tt,PageTitle:it,InputFile:st,NavigationLock:lt,getJSDataStreamChunk:dt,attachWebRendererInterop:function(t,n,o,r){if(S.has(t))throw new Error(`Interop methods are already registered for renderer ${t}`);S.set(t,n),Object.keys(o).length>0&&function(t,n,o){if(g)throw new Error("Dynamic root components have already been enabled.");g=t,m=n;for(const[t,r]of Object.entries(o)){const o=e.findJSFunction(t,0);for(const e of r)o(e,n[e])}}(D(t),o,r),I(),function(e){for(const t of C)t(e)}(t)}}};var ft;window.Blazor=pt,function(e){e[e.Trace=0]="Trace",e[e.Debug=1]="Debug",e[e.Information=2]="Information",e[e.Warning=3]="Warning",e[e.Error=4]="Error",e[e.Critical=5]="Critical",e[e.None=6]="None"}(ft||(ft={}));class gt{log(e,t){}}gt.instance=new gt;class mt{constructor(e){this.minLevel=e}log(e,t){if(e>=this.minLevel){const n=`[${(new Date).toISOString()}] ${ft[e]}: ${t}`;switch(e){case ft.Critical:case ft.Error:console.error(n);break;case ft.Warning:console.warn(n);break;case ft.Information:console.info(n);break;default:console.log(n)}}}}function yt(e,t){switch(t){case"webassembly":return bt(e,"webassembly");case"server":return function(e){return bt(e,"server").sort(((e,t)=>e.sequence-t.sequence))}(e);case"auto":return bt(e,"auto")}}const vt=/^\s*Blazor-Component-State:(?[a-zA-Z0-9+/=]+)$/;function wt(e){var t;if(e.nodeType===Node.COMMENT_NODE){const n=e.textContent||"",o=vt.exec(n),r=o&&o.groups&&o.groups.state;return r&&(null===(t=e.parentNode)||void 0===t||t.removeChild(e)),r}if(!e.hasChildNodes())return;const n=e.childNodes;for(let e=0;e.*)$/);function Et(e,t){const n=e.currentElement;var o,r,i;if(n&&n.nodeType===Node.COMMENT_NODE&&n.textContent){const s=_t.exec(n.textContent),a=s&&s.groups&&s.groups.descriptor;if(!a)return;!function(e){if(e.parentNode instanceof Document)throw new Error("Root components cannot be marked as interactive. The element must be rendered statically so that scripts are not evaluated multiple times.")}(n);try{const s=function(e){const t=JSON.parse(e),{type:n}=t;if("server"!==n&&"webassembly"!==n&&"auto"!==n)throw new Error(`Invalid component type '${n}'.`);return t}(a),c=function(e,t,n){const{prerenderId:o}=e;if(o){for(;n.next()&&n.currentElement;){const e=n.currentElement;if(e.nodeType!==Node.COMMENT_NODE)continue;if(!e.textContent)continue;const t=_t.exec(e.textContent),r=t&&t[1];if(r)return kt(r,o),e}throw new Error(`Could not find an end component comment for '${t}'.`)}}(s,n,e);if(t!==s.type)return;switch(s.type){case"webassembly":return r=n,i=c,It(o=s),{...o,uniqueId:St++,start:r,end:i};case"server":return function(e,t,n){return Ct(e),{...e,uniqueId:St++,start:t,end:n}}(s,n,c);case"auto":return function(e,t,n){return Ct(e),It(e),{...e,uniqueId:St++,start:t,end:n}}(s,n,c)}}catch(e){throw new Error(`Found malformed component comment at ${n.textContent}`)}}}let St=0;function Ct(e){const{descriptor:t,sequence:n}=e;if(!t)throw new Error("descriptor must be defined when using a descriptor.");if(void 0===n)throw new Error("sequence must be defined when using a descriptor.");if(!Number.isInteger(n))throw new Error(`Error parsing the sequence '${n}' for component '${JSON.stringify(e)}'`)}function It(e){const{assembly:t,typeName:n}=e;if(!t)throw new Error("assembly must be defined when using a descriptor.");if(!n)throw new Error("typeName must be defined when using a descriptor.");e.parameterDefinitions=e.parameterDefinitions&&atob(e.parameterDefinitions),e.parameterValues=e.parameterValues&&atob(e.parameterValues)}function kt(e,t){const n=JSON.parse(e);if(1!==Object.keys(n).length)throw new Error(`Invalid end of component comment: '${e}'`);const o=n.prerenderId;if(!o)throw new Error(`End of component comment must have a value for the prerendered property: '${e}'`);if(o!==t)throw new Error(`End of component comment prerendered property must match the start comment prerender id: '${t}', '${o}'`)}class Tt{constructor(e){this.childNodes=e,this.currentIndex=-1,this.length=e.length}next(){return this.currentIndex++,this.currentIndex{n+=`0x${e<16?"0":""}${e.toString(16)} `})),n.substr(0,n.length-1)}(e)}'`)):"string"==typeof e&&(n=`String data of length ${e.length}`,t&&(n+=`. Content: '${e}'`)),n}function Bt(e){return e&&"undefined"!=typeof ArrayBuffer&&(e instanceof ArrayBuffer||e.constructor&&"ArrayBuffer"===e.constructor.name)}async function Ft(e,t,n,o,r,i){const s={},[a,c]=Ht();s[a]=c,e.log(At.Trace,`(${t} transport) sending data. ${Lt(r,i.logMessageContent)}.`);const l=Bt(r)?"arraybuffer":"text",h=await n.post(o,{content:r,headers:{...s,...i.headers},responseType:l,timeout:i.timeout,withCredentials:i.withCredentials});e.log(At.Trace,`(${t} transport) request complete. Response status: ${h.statusCode}.`)}class Ot{constructor(e,t){this._subject=e,this._observer=t}dispose(){const e=this._subject.observers.indexOf(this._observer);e>-1&&this._subject.observers.splice(e,1),0===this._subject.observers.length&&this._subject.cancelCallback&&this._subject.cancelCallback().catch((e=>{}))}}class $t{constructor(e){this._minLevel=e,this.out=console}log(e,t){if(e>=this._minLevel){const n=`[${(new Date).toISOString()}] ${At[e]}: ${t}`;switch(e){case At.Critical:case At.Error:this.out.error(n);break;case At.Warning:this.out.warn(n);break;case At.Information:this.out.info(n);break;default:this.out.log(n)}}}}function Ht(){let e="X-SignalR-User-Agent";return Ut.isNode&&(e="User-Agent"),[e,jt(Mt,Wt(),Ut.isNode?"NodeJS":"Browser",qt())]}function jt(e,t,n,o){let r="Microsoft SignalR/";const i=e.split(".");return r+=`${i[0]}.${i[1]}`,r+=` (${e}; `,r+=t&&""!==t?`${t}; `:"Unknown OS; ",r+=`${n}`,r+=o?`; ${o}`:"; Unknown Runtime Version",r+=")",r}function Wt(){if(!Ut.isNode)return"";switch(process.platform){case"win32":return"Windows NT";case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}}function qt(){if(Ut.isNode)return process.versions.node}function zt(e){return e.stack?e.stack:e.message?e.message:`${e}`}class Jt{writeHandshakeRequest(e){return xt.write(JSON.stringify(e))}parseHandshakeResponse(e){let t,n;if(Bt(e)){const o=new Uint8Array(e),r=o.indexOf(xt.RecordSeparatorCode);if(-1===r)throw new Error("Message is incomplete.");const i=r+1;t=String.fromCharCode.apply(null,Array.prototype.slice.call(o.slice(0,i))),n=o.byteLength>i?o.slice(i).buffer:null}else{const o=e,r=o.indexOf(xt.RecordSeparator);if(-1===r)throw new Error("Message is incomplete.");const i=r+1;t=o.substring(0,i),n=o.length>i?o.substring(i):null}const o=xt.parse(t),r=JSON.parse(o[0]);if(r.type)throw new Error("Expected a handshake response from the server.");return[n,r]}}class Kt extends Error{constructor(e,t){const n=new.target.prototype;super(`${e}: Status code '${t}'`),this.statusCode=t,this.__proto__=n}}class Vt extends Error{constructor(e="A timeout occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class Xt extends Error{constructor(e="An abort occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class Gt extends Error{constructor(e,t){const n=new.target.prototype;super(e),this.transport=t,this.errorType="UnsupportedTransportError",this.__proto__=n}}class Yt extends Error{constructor(e,t){const n=new.target.prototype;super(e),this.transport=t,this.errorType="DisabledTransportError",this.__proto__=n}}class Qt extends Error{constructor(e,t){const n=new.target.prototype;super(e),this.transport=t,this.errorType="FailedToStartTransportError",this.__proto__=n}}class Zt extends Error{constructor(e){const t=new.target.prototype;super(e),this.errorType="FailedToNegotiateWithServerError",this.__proto__=t}}class en extends Error{constructor(e,t){const n=new.target.prototype;super(e),this.innerErrors=t,this.__proto__=n}}var tn,nn;!function(e){e[e.Invocation=1]="Invocation",e[e.StreamItem=2]="StreamItem",e[e.Completion=3]="Completion",e[e.StreamInvocation=4]="StreamInvocation",e[e.CancelInvocation=5]="CancelInvocation",e[e.Ping=6]="Ping",e[e.Close=7]="Close",e[e.Ack=8]="Ack",e[e.Sequence=9]="Sequence"}(tn||(tn={}));class on{constructor(){this.observers=[]}next(e){for(const t of this.observers)t.next(e)}error(e){for(const t of this.observers)t.error&&t.error(e)}complete(){for(const e of this.observers)e.complete&&e.complete()}subscribe(e){return this.observers.push(e),new Ot(this,e)}}class rn{constructor(e,t,n){this._bufferSize=1e5,this._messages=[],this._totalMessageCount=0,this._waitForSequenceMessage=!1,this._nextReceivingSequenceId=1,this._latestReceivedSequenceId=0,this._bufferedByteCount=0,this._reconnectInProgress=!1,this._protocol=e,this._connection=t,this._bufferSize=n}async _send(e){const t=this._protocol.writeMessage(e);let n=Promise.resolve();if(this._isInvocationMessage(e)){this._totalMessageCount++;let e=()=>{},o=()=>{};Bt(t)?this._bufferedByteCount+=t.byteLength:this._bufferedByteCount+=t.length,this._bufferedByteCount>=this._bufferSize&&(n=new Promise(((t,n)=>{e=t,o=n}))),this._messages.push(new sn(t,this._totalMessageCount,e,o))}try{this._reconnectInProgress||await this._connection.send(t)}catch{this._disconnected()}await n}_ack(e){let t=-1;for(let n=0;nthis._nextReceivingSequenceId?this._connection.stop(new Error("Sequence ID greater than amount of messages we've received.")):this._nextReceivingSequenceId=e.sequenceId}_disconnected(){this._reconnectInProgress=!0,this._waitForSequenceMessage=!0}async _resend(){const e=0!==this._messages.length?this._messages[0]._id:this._totalMessageCount+1;await this._connection.send(this._protocol.writeMessage({type:tn.Sequence,sequenceId:e}));const t=this._messages;for(const e of t)await this._connection.send(e._message);this._reconnectInProgress=!1}_dispose(e){null!=e||(e=new Error("Unable to reconnect to server."));for(const t of this._messages)t._rejector(e)}_isInvocationMessage(e){switch(e.type){case tn.Invocation:case tn.StreamItem:case tn.Completion:case tn.StreamInvocation:case tn.CancelInvocation:return!0;case tn.Close:case tn.Sequence:case tn.Ping:case tn.Ack:return!1}}_ackTimer(){void 0===this._ackTimerHandle&&(this._ackTimerHandle=setTimeout((async()=>{try{this._reconnectInProgress||await this._connection.send(this._protocol.writeMessage({type:tn.Ack,sequenceId:this._latestReceivedSequenceId}))}catch{}clearTimeout(this._ackTimerHandle),this._ackTimerHandle=void 0}),1e3))}}class sn{constructor(e,t,n,o){this._message=e,this._id=t,this._resolver=n,this._rejector=o}}!function(e){e.Disconnected="Disconnected",e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Reconnecting="Reconnecting"}(nn||(nn={}));class an{static create(e,t,n,o,r,i,s){return new an(e,t,n,o,r,i,s)}constructor(e,t,n,o,r,i,s){this._nextKeepAlive=0,this._freezeEventListener=()=>{this._logger.log(At.Warning,"The page is being frozen, this will likely lead to the connection being closed and messages being lost. For more information see the docs at https://learn.microsoft.com/aspnet/core/signalr/javascript-client#bsleep")},Pt.isRequired(e,"connection"),Pt.isRequired(t,"logger"),Pt.isRequired(n,"protocol"),this.serverTimeoutInMilliseconds=null!=r?r:3e4,this.keepAliveIntervalInMilliseconds=null!=i?i:15e3,this._statefulReconnectBufferSize=null!=s?s:1e5,this._logger=t,this._protocol=n,this.connection=e,this._reconnectPolicy=o,this._handshakeProtocol=new Jt,this.connection.onreceive=e=>this._processIncomingData(e),this.connection.onclose=e=>this._connectionClosed(e),this._callbacks={},this._methods={},this._closedCallbacks=[],this._reconnectingCallbacks=[],this._reconnectedCallbacks=[],this._invocationId=0,this._receivedHandshakeResponse=!1,this._connectionState=nn.Disconnected,this._connectionStarted=!1,this._cachedPingMessage=this._protocol.writeMessage({type:tn.Ping})}get state(){return this._connectionState}get connectionId(){return this.connection&&this.connection.connectionId||null}get baseUrl(){return this.connection.baseUrl||""}set baseUrl(e){if(this._connectionState!==nn.Disconnected&&this._connectionState!==nn.Reconnecting)throw new Error("The HubConnection must be in the Disconnected or Reconnecting state to change the url.");if(!e)throw new Error("The HubConnection url must be a valid url.");this.connection.baseUrl=e}start(){return this._startPromise=this._startWithStateTransitions(),this._startPromise}async _startWithStateTransitions(){if(this._connectionState!==nn.Disconnected)return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."));this._connectionState=nn.Connecting,this._logger.log(At.Debug,"Starting HubConnection.");try{await this._startInternal(),Ut.isBrowser&&window.document.addEventListener("freeze",this._freezeEventListener),this._connectionState=nn.Connected,this._connectionStarted=!0,this._logger.log(At.Debug,"HubConnection connected successfully.")}catch(e){return this._connectionState=nn.Disconnected,this._logger.log(At.Debug,`HubConnection failed to start successfully because of error '${e}'.`),Promise.reject(e)}}async _startInternal(){this._stopDuringStartError=void 0,this._receivedHandshakeResponse=!1;const e=new Promise(((e,t)=>{this._handshakeResolver=e,this._handshakeRejecter=t}));await this.connection.start(this._protocol.transferFormat);try{let t=this._protocol.version;this.connection.features.reconnect||(t=1);const n={protocol:this._protocol.name,version:t};if(this._logger.log(At.Debug,"Sending handshake request."),await this._sendMessage(this._handshakeProtocol.writeHandshakeRequest(n)),this._logger.log(At.Information,`Using HubProtocol '${this._protocol.name}'.`),this._cleanupTimeout(),this._resetTimeoutPeriod(),this._resetKeepAliveInterval(),await e,this._stopDuringStartError)throw this._stopDuringStartError;!!this.connection.features.reconnect&&(this._messageBuffer=new rn(this._protocol,this.connection,this._statefulReconnectBufferSize),this.connection.features.disconnected=this._messageBuffer._disconnected.bind(this._messageBuffer),this.connection.features.resend=()=>{if(this._messageBuffer)return this._messageBuffer._resend()}),this.connection.features.inherentKeepAlive||await this._sendMessage(this._cachedPingMessage)}catch(e){throw this._logger.log(At.Debug,`Hub handshake failed with error '${e}' during start(). Stopping HubConnection.`),this._cleanupTimeout(),this._cleanupPingTimer(),await this.connection.stop(e),e}}async stop(){const e=this._startPromise;this.connection.features.reconnect=!1,this._stopPromise=this._stopInternal(),await this._stopPromise;try{await e}catch(e){}}_stopInternal(e){if(this._connectionState===nn.Disconnected)return this._logger.log(At.Debug,`Call to HubConnection.stop(${e}) ignored because it is already in the disconnected state.`),Promise.resolve();if(this._connectionState===nn.Disconnecting)return this._logger.log(At.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnecting state.`),this._stopPromise;const t=this._connectionState;return this._connectionState=nn.Disconnecting,this._logger.log(At.Debug,"Stopping HubConnection."),this._reconnectDelayHandle?(this._logger.log(At.Debug,"Connection stopped during reconnect delay. Done reconnecting."),clearTimeout(this._reconnectDelayHandle),this._reconnectDelayHandle=void 0,this._completeClose(),Promise.resolve()):(t===nn.Connected&&this._sendCloseMessage(),this._cleanupTimeout(),this._cleanupPingTimer(),this._stopDuringStartError=e||new Xt("The connection was stopped before the hub handshake could complete."),this.connection.stop(e))}async _sendCloseMessage(){try{await this._sendWithProtocol(this._createCloseMessage())}catch{}}stream(e,...t){const[n,o]=this._replaceStreamingParams(t),r=this._createStreamInvocation(e,t,o);let i;const s=new on;return s.cancelCallback=()=>{const e=this._createCancelInvocation(r.invocationId);return delete this._callbacks[r.invocationId],i.then((()=>this._sendWithProtocol(e)))},this._callbacks[r.invocationId]=(e,t)=>{t?s.error(t):e&&(e.type===tn.Completion?e.error?s.error(new Error(e.error)):s.complete():s.next(e.item))},i=this._sendWithProtocol(r).catch((e=>{s.error(e),delete this._callbacks[r.invocationId]})),this._launchStreams(n,i),s}_sendMessage(e){return this._resetKeepAliveInterval(),this.connection.send(e)}_sendWithProtocol(e){return this._messageBuffer?this._messageBuffer._send(e):this._sendMessage(this._protocol.writeMessage(e))}send(e,...t){const[n,o]=this._replaceStreamingParams(t),r=this._sendWithProtocol(this._createInvocation(e,t,!0,o));return this._launchStreams(n,r),r}invoke(e,...t){const[n,o]=this._replaceStreamingParams(t),r=this._createInvocation(e,t,!1,o);return new Promise(((e,t)=>{this._callbacks[r.invocationId]=(n,o)=>{o?t(o):n&&(n.type===tn.Completion?n.error?t(new Error(n.error)):e(n.result):t(new Error(`Unexpected message type: ${n.type}`)))};const o=this._sendWithProtocol(r).catch((e=>{t(e),delete this._callbacks[r.invocationId]}));this._launchStreams(n,o)}))}on(e,t){e&&t&&(e=e.toLowerCase(),this._methods[e]||(this._methods[e]=[]),-1===this._methods[e].indexOf(t)&&this._methods[e].push(t))}off(e,t){if(!e)return;e=e.toLowerCase();const n=this._methods[e];if(n)if(t){const o=n.indexOf(t);-1!==o&&(n.splice(o,1),0===n.length&&delete this._methods[e])}else delete this._methods[e]}onclose(e){e&&this._closedCallbacks.push(e)}onreconnecting(e){e&&this._reconnectingCallbacks.push(e)}onreconnected(e){e&&this._reconnectedCallbacks.push(e)}_processIncomingData(e){if(this._cleanupTimeout(),this._receivedHandshakeResponse||(e=this._processHandshakeResponse(e),this._receivedHandshakeResponse=!0),e){const t=this._protocol.parseMessages(e,this._logger);for(const e of t)if(!this._messageBuffer||this._messageBuffer._shouldProcessMessage(e))switch(e.type){case tn.Invocation:this._invokeClientMethod(e);break;case tn.StreamItem:case tn.Completion:{const t=this._callbacks[e.invocationId];if(t){e.type===tn.Completion&&delete this._callbacks[e.invocationId];try{t(e)}catch(e){this._logger.log(At.Error,`Stream callback threw error: ${zt(e)}`)}}break}case tn.Ping:break;case tn.Close:{this._logger.log(At.Information,"Close message received from server.");const t=e.error?new Error("Server returned an error on close: "+e.error):void 0;!0===e.allowReconnect?this.connection.stop(t):this._stopPromise=this._stopInternal(t);break}case tn.Ack:this._messageBuffer&&this._messageBuffer._ack(e);break;case tn.Sequence:this._messageBuffer&&this._messageBuffer._resetSequence(e);break;default:this._logger.log(At.Warning,`Invalid message type: ${e.type}.`)}}this._resetTimeoutPeriod()}_processHandshakeResponse(e){let t,n;try{[n,t]=this._handshakeProtocol.parseHandshakeResponse(e)}catch(e){const t="Error parsing handshake response: "+e;this._logger.log(At.Error,t);const n=new Error(t);throw this._handshakeRejecter(n),n}if(t.error){const e="Server returned handshake error: "+t.error;this._logger.log(At.Error,e);const n=new Error(e);throw this._handshakeRejecter(n),n}return this._logger.log(At.Debug,"Server handshake complete."),this._handshakeResolver(),n}_resetKeepAliveInterval(){this.connection.features.inherentKeepAlive||(this._nextKeepAlive=(new Date).getTime()+this.keepAliveIntervalInMilliseconds,this._cleanupPingTimer())}_resetTimeoutPeriod(){if(!(this.connection.features&&this.connection.features.inherentKeepAlive||(this._timeoutHandle=setTimeout((()=>this.serverTimeout()),this.serverTimeoutInMilliseconds),void 0!==this._pingServerHandle))){let e=this._nextKeepAlive-(new Date).getTime();e<0&&(e=0),this._pingServerHandle=setTimeout((async()=>{if(this._connectionState===nn.Connected)try{await this._sendMessage(this._cachedPingMessage)}catch{this._cleanupPingTimer()}}),e)}}serverTimeout(){this.connection.stop(new Error("Server timeout elapsed without receiving a message from the server."))}async _invokeClientMethod(e){const t=e.target.toLowerCase(),n=this._methods[t];if(!n)return this._logger.log(At.Warning,`No client method with the name '${t}' found.`),void(e.invocationId&&(this._logger.log(At.Warning,`No result given for '${t}' method and invocation ID '${e.invocationId}'.`),await this._sendWithProtocol(this._createCompletionMessage(e.invocationId,"Client didn't provide a result.",null))));const o=n.slice(),r=!!e.invocationId;let i,s,a;for(const n of o)try{const o=i;i=await n.apply(this,e.arguments),r&&i&&o&&(this._logger.log(At.Error,`Multiple results provided for '${t}'. Sending error to server.`),a=this._createCompletionMessage(e.invocationId,"Client provided multiple results.",null)),s=void 0}catch(e){s=e,this._logger.log(At.Error,`A callback for the method '${t}' threw error '${e}'.`)}a?await this._sendWithProtocol(a):r?(s?a=this._createCompletionMessage(e.invocationId,`${s}`,null):void 0!==i?a=this._createCompletionMessage(e.invocationId,null,i):(this._logger.log(At.Warning,`No result given for '${t}' method and invocation ID '${e.invocationId}'.`),a=this._createCompletionMessage(e.invocationId,"Client didn't provide a result.",null)),await this._sendWithProtocol(a)):i&&this._logger.log(At.Error,`Result given for '${t}' method but server is not expecting a result.`)}_connectionClosed(e){this._logger.log(At.Debug,`HubConnection.connectionClosed(${e}) called while in state ${this._connectionState}.`),this._stopDuringStartError=this._stopDuringStartError||e||new Xt("The underlying connection was closed before the hub handshake could complete."),this._handshakeResolver&&this._handshakeResolver(),this._cancelCallbacksWithError(e||new Error("Invocation canceled due to the underlying connection being closed.")),this._cleanupTimeout(),this._cleanupPingTimer(),this._connectionState===nn.Disconnecting?this._completeClose(e):this._connectionState===nn.Connected&&this._reconnectPolicy?this._reconnect(e):this._connectionState===nn.Connected&&this._completeClose(e)}_completeClose(e){if(this._connectionStarted){this._connectionState=nn.Disconnected,this._connectionStarted=!1,this._messageBuffer&&(this._messageBuffer._dispose(null!=e?e:new Error("Connection closed.")),this._messageBuffer=void 0),Ut.isBrowser&&window.document.removeEventListener("freeze",this._freezeEventListener);try{this._closedCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(At.Error,`An onclose callback called with error '${e}' threw error '${t}'.`)}}}async _reconnect(e){const t=Date.now();let n=0,o=void 0!==e?e:new Error("Attempting to reconnect due to a unknown error."),r=this._getNextRetryDelay(n++,0,o);if(null===r)return this._logger.log(At.Debug,"Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt."),void this._completeClose(e);if(this._connectionState=nn.Reconnecting,e?this._logger.log(At.Information,`Connection reconnecting because of error '${e}'.`):this._logger.log(At.Information,"Connection reconnecting."),0!==this._reconnectingCallbacks.length){try{this._reconnectingCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(At.Error,`An onreconnecting callback called with error '${e}' threw error '${t}'.`)}if(this._connectionState!==nn.Reconnecting)return void this._logger.log(At.Debug,"Connection left the reconnecting state in onreconnecting callback. Done reconnecting.")}for(;null!==r;){if(this._logger.log(At.Information,`Reconnect attempt number ${n} will start in ${r} ms.`),await new Promise((e=>{this._reconnectDelayHandle=setTimeout(e,r)})),this._reconnectDelayHandle=void 0,this._connectionState!==nn.Reconnecting)return void this._logger.log(At.Debug,"Connection left the reconnecting state during reconnect delay. Done reconnecting.");try{if(await this._startInternal(),this._connectionState=nn.Connected,this._logger.log(At.Information,"HubConnection reconnected successfully."),0!==this._reconnectedCallbacks.length)try{this._reconnectedCallbacks.forEach((e=>e.apply(this,[this.connection.connectionId])))}catch(e){this._logger.log(At.Error,`An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${e}'.`)}return}catch(e){if(this._logger.log(At.Information,`Reconnect attempt failed because of error '${e}'.`),this._connectionState!==nn.Reconnecting)return this._logger.log(At.Debug,`Connection moved to the '${this._connectionState}' from the reconnecting state during reconnect attempt. Done reconnecting.`),void(this._connectionState===nn.Disconnecting&&this._completeClose());o=e instanceof Error?e:new Error(e.toString()),r=this._getNextRetryDelay(n++,Date.now()-t,o)}}this._logger.log(At.Information,`Reconnect retries have been exhausted after ${Date.now()-t} ms and ${n} failed attempts. Connection disconnecting.`),this._completeClose()}_getNextRetryDelay(e,t,n){try{return this._reconnectPolicy.nextRetryDelayInMilliseconds({elapsedMilliseconds:t,previousRetryCount:e,retryReason:n})}catch(n){return this._logger.log(At.Error,`IRetryPolicy.nextRetryDelayInMilliseconds(${e}, ${t}) threw error '${n}'.`),null}}_cancelCallbacksWithError(e){const t=this._callbacks;this._callbacks={},Object.keys(t).forEach((n=>{const o=t[n];try{o(null,e)}catch(t){this._logger.log(At.Error,`Stream 'error' callback called with '${e}' threw error: ${zt(t)}`)}}))}_cleanupPingTimer(){this._pingServerHandle&&(clearTimeout(this._pingServerHandle),this._pingServerHandle=void 0)}_cleanupTimeout(){this._timeoutHandle&&clearTimeout(this._timeoutHandle)}_createInvocation(e,t,n,o){if(n)return 0!==o.length?{arguments:t,streamIds:o,target:e,type:tn.Invocation}:{arguments:t,target:e,type:tn.Invocation};{const n=this._invocationId;return this._invocationId++,0!==o.length?{arguments:t,invocationId:n.toString(),streamIds:o,target:e,type:tn.Invocation}:{arguments:t,invocationId:n.toString(),target:e,type:tn.Invocation}}}_launchStreams(e,t){if(0!==e.length){t||(t=Promise.resolve());for(const n in e)e[n].subscribe({complete:()=>{t=t.then((()=>this._sendWithProtocol(this._createCompletionMessage(n))))},error:e=>{let o;o=e instanceof Error?e.message:e&&e.toString?e.toString():"Unknown error",t=t.then((()=>this._sendWithProtocol(this._createCompletionMessage(n,o))))},next:e=>{t=t.then((()=>this._sendWithProtocol(this._createStreamItemMessage(n,e))))}})}}_replaceStreamingParams(e){const t=[],n=[];for(let o=0;o0)&&(t=!1,this._accessToken=await this._accessTokenFactory()),this._setAuthorizationHeader(e);const n=await this._innerClient.send(e);return t&&401===n.statusCode&&this._accessTokenFactory?(this._accessToken=await this._accessTokenFactory(),this._setAuthorizationHeader(e),await this._innerClient.send(e)):n}_setAuthorizationHeader(e){e.headers||(e.headers={}),this._accessToken?e.headers[hn.Authorization]=`Bearer ${this._accessToken}`:this._accessTokenFactory&&e.headers[hn.Authorization]&&delete e.headers[hn.Authorization]}getCookieString(e){return this._innerClient.getCookieString(e)}}class fn extends un{constructor(e){super(),this._logger=e;const t={_fetchType:void 0,_jar:void 0};var o;o=t,"undefined"==typeof fetch&&(o._jar=new(n(628).CookieJar),"undefined"==typeof fetch?o._fetchType=n(200):o._fetchType=fetch,o._fetchType=n(203)(o._fetchType,o._jar),1)?(this._fetchType=t._fetchType,this._jar=t._jar):this._fetchType=fetch.bind(function(){if("undefined"!=typeof globalThis)return globalThis;if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if(void 0!==n.g)return n.g;throw new Error("could not find global")}()),this._abortControllerType=AbortController;const r={_abortControllerType:this._abortControllerType};(function(e){return"undefined"==typeof AbortController&&(e._abortControllerType=n(778),!0)})(r)&&(this._abortControllerType=r._abortControllerType)}async send(e){if(e.abortSignal&&e.abortSignal.aborted)throw new Xt;if(!e.method)throw new Error("No method defined.");if(!e.url)throw new Error("No url defined.");const t=new this._abortControllerType;let n;e.abortSignal&&(e.abortSignal.onabort=()=>{t.abort(),n=new Xt});let o,r=null;if(e.timeout){const o=e.timeout;r=setTimeout((()=>{t.abort(),this._logger.log(At.Warning,"Timeout from HTTP request."),n=new Vt}),o)}""===e.content&&(e.content=void 0),e.content&&(e.headers=e.headers||{},Bt(e.content)?e.headers["Content-Type"]="application/octet-stream":e.headers["Content-Type"]="text/plain;charset=UTF-8");try{o=await this._fetchType(e.url,{body:e.content,cache:"no-cache",credentials:!0===e.withCredentials?"include":"same-origin",headers:{"X-Requested-With":"XMLHttpRequest",...e.headers},method:e.method,mode:"cors",redirect:"follow",signal:t.signal})}catch(e){if(n)throw n;throw this._logger.log(At.Warning,`Error from HTTP request. ${e}.`),e}finally{r&&clearTimeout(r),e.abortSignal&&(e.abortSignal.onabort=null)}if(!o.ok){const e=await gn(o,"text");throw new Kt(e||o.statusText,o.status)}const i=gn(o,e.responseType),s=await i;return new dn(o.status,o.statusText,s)}getCookieString(e){return""}}function gn(e,t){let n;switch(t){case"arraybuffer":n=e.arrayBuffer();break;case"text":default:n=e.text();break;case"blob":case"document":case"json":throw new Error(`${t} is not supported.`)}return n}class mn extends un{constructor(e){super(),this._logger=e}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new Xt):e.method?e.url?new Promise(((t,n)=>{const o=new XMLHttpRequest;o.open(e.method,e.url,!0),o.withCredentials=void 0===e.withCredentials||e.withCredentials,o.setRequestHeader("X-Requested-With","XMLHttpRequest"),""===e.content&&(e.content=void 0),e.content&&(Bt(e.content)?o.setRequestHeader("Content-Type","application/octet-stream"):o.setRequestHeader("Content-Type","text/plain;charset=UTF-8"));const r=e.headers;r&&Object.keys(r).forEach((e=>{o.setRequestHeader(e,r[e])})),e.responseType&&(o.responseType=e.responseType),e.abortSignal&&(e.abortSignal.onabort=()=>{o.abort(),n(new Xt)}),e.timeout&&(o.timeout=e.timeout),o.onload=()=>{e.abortSignal&&(e.abortSignal.onabort=null),o.status>=200&&o.status<300?t(new dn(o.status,o.statusText,o.response||o.responseText)):n(new Kt(o.response||o.responseText||o.statusText,o.status))},o.onerror=()=>{this._logger.log(At.Warning,`Error from HTTP request. ${o.status}: ${o.statusText}.`),n(new Kt(o.statusText,o.status))},o.ontimeout=()=>{this._logger.log(At.Warning,"Timeout from HTTP request."),n(new Vt)},o.send(e.content)})):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}}class yn extends un{constructor(e){if(super(),"undefined"!=typeof fetch)this._httpClient=new fn(e);else{if("undefined"==typeof XMLHttpRequest)throw new Error("No usable HttpClient found.");this._httpClient=new mn(e)}}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new Xt):e.method?e.url?this._httpClient.send(e):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}getCookieString(e){return this._httpClient.getCookieString(e)}}var vn,wn;!function(e){e[e.None=0]="None",e[e.WebSockets=1]="WebSockets",e[e.ServerSentEvents=2]="ServerSentEvents",e[e.LongPolling=4]="LongPolling"}(vn||(vn={})),function(e){e[e.Text=1]="Text",e[e.Binary=2]="Binary"}(wn||(wn={}));class bn{constructor(){this._isAborted=!1,this.onabort=null}abort(){this._isAborted||(this._isAborted=!0,this.onabort&&this.onabort())}get signal(){return this}get aborted(){return this._isAborted}}class _n{get pollAborted(){return this._pollAbort.aborted}constructor(e,t,n){this._httpClient=e,this._logger=t,this._pollAbort=new bn,this._options=n,this._running=!1,this.onreceive=null,this.onclose=null}async connect(e,t){if(Pt.isRequired(e,"url"),Pt.isRequired(t,"transferFormat"),Pt.isIn(t,wn,"transferFormat"),this._url=e,this._logger.log(At.Trace,"(LongPolling transport) Connecting."),t===wn.Binary&&"undefined"!=typeof XMLHttpRequest&&"string"!=typeof(new XMLHttpRequest).responseType)throw new Error("Binary protocols over XmlHttpRequest not implementing advanced features are not supported.");const[n,o]=Ht(),r={[n]:o,...this._options.headers},i={abortSignal:this._pollAbort.signal,headers:r,timeout:1e5,withCredentials:this._options.withCredentials};t===wn.Binary&&(i.responseType="arraybuffer");const s=`${e}&_=${Date.now()}`;this._logger.log(At.Trace,`(LongPolling transport) polling: ${s}.`);const a=await this._httpClient.get(s,i);200!==a.statusCode?(this._logger.log(At.Error,`(LongPolling transport) Unexpected response code: ${a.statusCode}.`),this._closeError=new Kt(a.statusText||"",a.statusCode),this._running=!1):this._running=!0,this._receiving=this._poll(this._url,i)}async _poll(e,t){try{for(;this._running;)try{const n=`${e}&_=${Date.now()}`;this._logger.log(At.Trace,`(LongPolling transport) polling: ${n}.`);const o=await this._httpClient.get(n,t);204===o.statusCode?(this._logger.log(At.Information,"(LongPolling transport) Poll terminated by server."),this._running=!1):200!==o.statusCode?(this._logger.log(At.Error,`(LongPolling transport) Unexpected response code: ${o.statusCode}.`),this._closeError=new Kt(o.statusText||"",o.statusCode),this._running=!1):o.content?(this._logger.log(At.Trace,`(LongPolling transport) data received. ${Lt(o.content,this._options.logMessageContent)}.`),this.onreceive&&this.onreceive(o.content)):this._logger.log(At.Trace,"(LongPolling transport) Poll timed out, reissuing.")}catch(e){this._running?e instanceof Vt?this._logger.log(At.Trace,"(LongPolling transport) Poll timed out, reissuing."):(this._closeError=e,this._running=!1):this._logger.log(At.Trace,`(LongPolling transport) Poll errored after shutdown: ${e.message}`)}}finally{this._logger.log(At.Trace,"(LongPolling transport) Polling complete."),this.pollAborted||this._raiseOnClose()}}async send(e){return this._running?Ft(this._logger,"LongPolling",this._httpClient,this._url,e,this._options):Promise.reject(new Error("Cannot send until the transport is connected"))}async stop(){this._logger.log(At.Trace,"(LongPolling transport) Stopping polling."),this._running=!1,this._pollAbort.abort();try{await this._receiving,this._logger.log(At.Trace,`(LongPolling transport) sending DELETE request to ${this._url}.`);const e={},[t,n]=Ht();e[t]=n;const o={headers:{...e,...this._options.headers},timeout:this._options.timeout,withCredentials:this._options.withCredentials};let r;try{await this._httpClient.delete(this._url,o)}catch(e){r=e}r?r instanceof Kt&&(404===r.statusCode?this._logger.log(At.Trace,"(LongPolling transport) A 404 response was returned from sending a DELETE request."):this._logger.log(At.Trace,`(LongPolling transport) Error sending a DELETE request: ${r}`)):this._logger.log(At.Trace,"(LongPolling transport) DELETE request accepted.")}finally{this._logger.log(At.Trace,"(LongPolling transport) Stop finished."),this._raiseOnClose()}}_raiseOnClose(){if(this.onclose){let e="(LongPolling transport) Firing onclose event.";this._closeError&&(e+=" Error: "+this._closeError),this._logger.log(At.Trace,e),this.onclose(this._closeError)}}}class En{constructor(e,t,n,o){this._httpClient=e,this._accessToken=t,this._logger=n,this._options=o,this.onreceive=null,this.onclose=null}async connect(e,t){return Pt.isRequired(e,"url"),Pt.isRequired(t,"transferFormat"),Pt.isIn(t,wn,"transferFormat"),this._logger.log(At.Trace,"(SSE transport) Connecting."),this._url=e,this._accessToken&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(this._accessToken)}`),new Promise(((n,o)=>{let r,i=!1;if(t===wn.Text){if(Ut.isBrowser||Ut.isWebWorker)r=new this._options.EventSource(e,{withCredentials:this._options.withCredentials});else{const t=this._httpClient.getCookieString(e),n={};n.Cookie=t;const[o,i]=Ht();n[o]=i,r=new this._options.EventSource(e,{withCredentials:this._options.withCredentials,headers:{...n,...this._options.headers}})}try{r.onmessage=e=>{if(this.onreceive)try{this._logger.log(At.Trace,`(SSE transport) data received. ${Lt(e.data,this._options.logMessageContent)}.`),this.onreceive(e.data)}catch(e){return void this._close(e)}},r.onerror=e=>{i?this._close():o(new Error("EventSource failed to connect. The connection could not be found on the server, either the connection ID is not present on the server, or a proxy is refusing/buffering the connection. If you have multiple servers check that sticky sessions are enabled."))},r.onopen=()=>{this._logger.log(At.Information,`SSE connected to ${this._url}`),this._eventSource=r,i=!0,n()}}catch(e){return void o(e)}}else o(new Error("The Server-Sent Events transport only supports the 'Text' transfer format"))}))}async send(e){return this._eventSource?Ft(this._logger,"SSE",this._httpClient,this._url,e,this._options):Promise.reject(new Error("Cannot send until the transport is connected"))}stop(){return this._close(),Promise.resolve()}_close(e){this._eventSource&&(this._eventSource.close(),this._eventSource=void 0,this.onclose&&this.onclose(e))}}class Sn{constructor(e,t,n,o,r,i){this._logger=n,this._accessTokenFactory=t,this._logMessageContent=o,this._webSocketConstructor=r,this._httpClient=e,this.onreceive=null,this.onclose=null,this._headers=i}async connect(e,t){let n;return Pt.isRequired(e,"url"),Pt.isRequired(t,"transferFormat"),Pt.isIn(t,wn,"transferFormat"),this._logger.log(At.Trace,"(WebSockets transport) Connecting."),this._accessTokenFactory&&(n=await this._accessTokenFactory()),new Promise(((o,r)=>{let i;e=e.replace(/^http/,"ws");const s=this._httpClient.getCookieString(e);let a=!1;if(Ut.isReactNative){const t={},[o,r]=Ht();t[o]=r,n&&(t[hn.Authorization]=`Bearer ${n}`),s&&(t[hn.Cookie]=s),i=new this._webSocketConstructor(e,void 0,{headers:{...t,...this._headers}})}else n&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(n)}`);i||(i=new this._webSocketConstructor(e)),t===wn.Binary&&(i.binaryType="arraybuffer"),i.onopen=t=>{this._logger.log(At.Information,`WebSocket connected to ${e}.`),this._webSocket=i,a=!0,o()},i.onerror=e=>{let t=null;t="undefined"!=typeof ErrorEvent&&e instanceof ErrorEvent?e.error:"There was an error with the transport",this._logger.log(At.Information,`(WebSockets transport) ${t}.`)},i.onmessage=e=>{if(this._logger.log(At.Trace,`(WebSockets transport) data received. ${Lt(e.data,this._logMessageContent)}.`),this.onreceive)try{this.onreceive(e.data)}catch(e){return void this._close(e)}},i.onclose=e=>{if(a)this._close(e);else{let t=null;t="undefined"!=typeof ErrorEvent&&e instanceof ErrorEvent?e.error:"WebSocket failed to connect. The connection could not be found on the server, either the endpoint may not be a SignalR endpoint, the connection ID is not present on the server, or there is a proxy blocking WebSockets. If you have multiple servers check that sticky sessions are enabled.",r(new Error(t))}}}))}send(e){return this._webSocket&&this._webSocket.readyState===this._webSocketConstructor.OPEN?(this._logger.log(At.Trace,`(WebSockets transport) sending data. ${Lt(e,this._logMessageContent)}.`),this._webSocket.send(e),Promise.resolve()):Promise.reject("WebSocket is not in the OPEN state")}stop(){return this._webSocket&&this._close(void 0),Promise.resolve()}_close(e){this._webSocket&&(this._webSocket.onclose=()=>{},this._webSocket.onmessage=()=>{},this._webSocket.onerror=()=>{},this._webSocket.close(),this._webSocket=void 0),this._logger.log(At.Trace,"(WebSockets transport) socket closed."),this.onclose&&(!this._isCloseEvent(e)||!1!==e.wasClean&&1e3===e.code?e instanceof Error?this.onclose(e):this.onclose():this.onclose(new Error(`WebSocket closed with status code: ${e.code} (${e.reason||"no reason given"}).`)))}_isCloseEvent(e){return e&&"boolean"==typeof e.wasClean&&"number"==typeof e.code}}class Cn{constructor(e,t={}){if(this._stopPromiseResolver=()=>{},this.features={},this._negotiateVersion=1,Pt.isRequired(e,"url"),this._logger=function(e){return void 0===e?new $t(At.Information):null===e?Nt.instance:void 0!==e.log?e:new $t(e)}(t.logger),this.baseUrl=this._resolveUrl(e),(t=t||{}).logMessageContent=void 0!==t.logMessageContent&&t.logMessageContent,"boolean"!=typeof t.withCredentials&&void 0!==t.withCredentials)throw new Error("withCredentials option was not a 'boolean' or 'undefined' value");t.withCredentials=void 0===t.withCredentials||t.withCredentials,t.timeout=void 0===t.timeout?1e5:t.timeout,"undefined"==typeof WebSocket||t.WebSocket||(t.WebSocket=WebSocket),"undefined"==typeof EventSource||t.EventSource||(t.EventSource=EventSource),this._httpClient=new pn(t.httpClient||new yn(this._logger),t.accessTokenFactory),this._connectionState="Disconnected",this._connectionStarted=!1,this._options=t,this.onreceive=null,this.onclose=null}async start(e){if(e=e||wn.Binary,Pt.isIn(e,wn,"transferFormat"),this._logger.log(At.Debug,`Starting connection with transfer format '${wn[e]}'.`),"Disconnected"!==this._connectionState)return Promise.reject(new Error("Cannot start an HttpConnection that is not in the 'Disconnected' state."));if(this._connectionState="Connecting",this._startInternalPromise=this._startInternal(e),await this._startInternalPromise,"Disconnecting"===this._connectionState){const e="Failed to start the HttpConnection before stop() was called.";return this._logger.log(At.Error,e),await this._stopPromise,Promise.reject(new Xt(e))}if("Connected"!==this._connectionState){const e="HttpConnection.startInternal completed gracefully but didn't enter the connection into the connected state!";return this._logger.log(At.Error,e),Promise.reject(new Xt(e))}this._connectionStarted=!0}send(e){return"Connected"!==this._connectionState?Promise.reject(new Error("Cannot send data if the connection is not in the 'Connected' State.")):(this._sendQueue||(this._sendQueue=new In(this.transport)),this._sendQueue.send(e))}async stop(e){return"Disconnected"===this._connectionState?(this._logger.log(At.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnected state.`),Promise.resolve()):"Disconnecting"===this._connectionState?(this._logger.log(At.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnecting state.`),this._stopPromise):(this._connectionState="Disconnecting",this._stopPromise=new Promise((e=>{this._stopPromiseResolver=e})),await this._stopInternal(e),void await this._stopPromise)}async _stopInternal(e){this._stopError=e;try{await this._startInternalPromise}catch(e){}if(this.transport){try{await this.transport.stop()}catch(e){this._logger.log(At.Error,`HttpConnection.transport.stop() threw error '${e}'.`),this._stopConnection()}this.transport=void 0}else this._logger.log(At.Debug,"HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.")}async _startInternal(e){let t=this.baseUrl;this._accessTokenFactory=this._options.accessTokenFactory,this._httpClient._accessTokenFactory=this._accessTokenFactory;try{if(this._options.skipNegotiation){if(this._options.transport!==vn.WebSockets)throw new Error("Negotiation can only be skipped when using the WebSocket transport directly.");this.transport=this._constructTransport(vn.WebSockets),await this._startTransport(t,e)}else{let n=null,o=0;do{if(n=await this._getNegotiationResponse(t),"Disconnecting"===this._connectionState||"Disconnected"===this._connectionState)throw new Xt("The connection was stopped during negotiation.");if(n.error)throw new Error(n.error);if(n.ProtocolVersion)throw new Error("Detected a connection attempt to an ASP.NET SignalR Server. This client only supports connecting to an ASP.NET Core SignalR Server. See https://aka.ms/signalr-core-differences for details.");if(n.url&&(t=n.url),n.accessToken){const e=n.accessToken;this._accessTokenFactory=()=>e,this._httpClient._accessToken=e,this._httpClient._accessTokenFactory=void 0}o++}while(n.url&&o<100);if(100===o&&n.url)throw new Error("Negotiate redirection limit exceeded.");await this._createTransport(t,this._options.transport,n,e)}this.transport instanceof _n&&(this.features.inherentKeepAlive=!0),"Connecting"===this._connectionState&&(this._logger.log(At.Debug,"The HttpConnection connected successfully."),this._connectionState="Connected")}catch(e){return this._logger.log(At.Error,"Failed to start the connection: "+e),this._connectionState="Disconnected",this.transport=void 0,this._stopPromiseResolver(),Promise.reject(e)}}async _getNegotiationResponse(e){const t={},[n,o]=Ht();t[n]=o;const r=this._resolveNegotiateUrl(e);this._logger.log(At.Debug,`Sending negotiation request: ${r}.`);try{const e=await this._httpClient.post(r,{content:"",headers:{...t,...this._options.headers},timeout:this._options.timeout,withCredentials:this._options.withCredentials});if(200!==e.statusCode)return Promise.reject(new Error(`Unexpected status code returned from negotiate '${e.statusCode}'`));const n=JSON.parse(e.content);return(!n.negotiateVersion||n.negotiateVersion<1)&&(n.connectionToken=n.connectionId),n.useStatefulReconnect&&!0!==this._options._useStatefulReconnect?Promise.reject(new Zt("Client didn't negotiate Stateful Reconnect but the server did.")):n}catch(e){let t="Failed to complete negotiation with the server: "+e;return e instanceof Kt&&404===e.statusCode&&(t+=" Either this is not a SignalR endpoint or there is a proxy blocking the connection."),this._logger.log(At.Error,t),Promise.reject(new Zt(t))}}_createConnectUrl(e,t){return t?e+(-1===e.indexOf("?")?"?":"&")+`id=${t}`:e}async _createTransport(e,t,n,o){let r=this._createConnectUrl(e,n.connectionToken);if(this._isITransport(t))return this._logger.log(At.Debug,"Connection was provided an instance of ITransport, using that directly."),this.transport=t,await this._startTransport(r,o),void(this.connectionId=n.connectionId);const i=[],s=n.availableTransports||[];let a=n;for(const n of s){const s=this._resolveTransportOrError(n,t,o,!0===(null==a?void 0:a.useStatefulReconnect));if(s instanceof Error)i.push(`${n.transport} failed:`),i.push(s);else if(this._isITransport(s)){if(this.transport=s,!a){try{a=await this._getNegotiationResponse(e)}catch(e){return Promise.reject(e)}r=this._createConnectUrl(e,a.connectionToken)}try{return await this._startTransport(r,o),void(this.connectionId=a.connectionId)}catch(e){if(this._logger.log(At.Error,`Failed to start the transport '${n.transport}': ${e}`),a=void 0,i.push(new Qt(`${n.transport} failed: ${e}`,vn[n.transport])),"Connecting"!==this._connectionState){const e="Failed to select transport before stop() was called.";return this._logger.log(At.Debug,e),Promise.reject(new Xt(e))}}}}return i.length>0?Promise.reject(new en(`Unable to connect to the server with any of the available transports. ${i.join(" ")}`,i)):Promise.reject(new Error("None of the transports supported by the client are supported by the server."))}_constructTransport(e){switch(e){case vn.WebSockets:if(!this._options.WebSocket)throw new Error("'WebSocket' is not supported in your environment.");return new Sn(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent,this._options.WebSocket,this._options.headers||{});case vn.ServerSentEvents:if(!this._options.EventSource)throw new Error("'EventSource' is not supported in your environment.");return new En(this._httpClient,this._httpClient._accessToken,this._logger,this._options);case vn.LongPolling:return new _n(this._httpClient,this._logger,this._options);default:throw new Error(`Unknown transport: ${e}.`)}}_startTransport(e,t){return this.transport.onreceive=this.onreceive,this.features.reconnect?this.transport.onclose=async n=>{let o=!1;if(this.features.reconnect){try{this.features.disconnected(),await this.transport.connect(e,t),await this.features.resend()}catch{o=!0}o&&this._stopConnection(n)}else this._stopConnection(n)}:this.transport.onclose=e=>this._stopConnection(e),this.transport.connect(e,t)}_resolveTransportOrError(e,t,n,o){const r=vn[e.transport];if(null==r)return this._logger.log(At.Debug,`Skipping transport '${e.transport}' because it is not supported by this client.`),new Error(`Skipping transport '${e.transport}' because it is not supported by this client.`);if(!function(e,t){return!e||0!=(t&e)}(t,r))return this._logger.log(At.Debug,`Skipping transport '${vn[r]}' because it was disabled by the client.`),new Yt(`'${vn[r]}' is disabled by the client.`,r);if(!(e.transferFormats.map((e=>wn[e])).indexOf(n)>=0))return this._logger.log(At.Debug,`Skipping transport '${vn[r]}' because it does not support the requested transfer format '${wn[n]}'.`),new Error(`'${vn[r]}' does not support ${wn[n]}.`);if(r===vn.WebSockets&&!this._options.WebSocket||r===vn.ServerSentEvents&&!this._options.EventSource)return this._logger.log(At.Debug,`Skipping transport '${vn[r]}' because it is not supported in your environment.'`),new Gt(`'${vn[r]}' is not supported in your environment.`,r);this._logger.log(At.Debug,`Selecting transport '${vn[r]}'.`);try{return this.features.reconnect=r===vn.WebSockets?o:void 0,this._constructTransport(r)}catch(e){return e}}_isITransport(e){return e&&"object"==typeof e&&"connect"in e}_stopConnection(e){if(this._logger.log(At.Debug,`HttpConnection.stopConnection(${e}) called while in state ${this._connectionState}.`),this.transport=void 0,e=this._stopError||e,this._stopError=void 0,"Disconnected"!==this._connectionState){if("Connecting"===this._connectionState)throw this._logger.log(At.Warning,`Call to HttpConnection.stopConnection(${e}) was ignored because the connection is still in the connecting state.`),new Error(`HttpConnection.stopConnection(${e}) was called while the connection is still in the connecting state.`);if("Disconnecting"===this._connectionState&&this._stopPromiseResolver(),e?this._logger.log(At.Error,`Connection disconnected with error '${e}'.`):this._logger.log(At.Information,"Connection disconnected."),this._sendQueue&&(this._sendQueue.stop().catch((e=>{this._logger.log(At.Error,`TransportSendQueue.stop() threw error '${e}'.`)})),this._sendQueue=void 0),this.connectionId=void 0,this._connectionState="Disconnected",this._connectionStarted){this._connectionStarted=!1;try{this.onclose&&this.onclose(e)}catch(t){this._logger.log(At.Error,`HttpConnection.onclose(${e}) threw error '${t}'.`)}}}else this._logger.log(At.Debug,`Call to HttpConnection.stopConnection(${e}) was ignored because the connection is already in the disconnected state.`)}_resolveUrl(e){if(0===e.lastIndexOf("https://",0)||0===e.lastIndexOf("http://",0))return e;if(!Ut.isBrowser)throw new Error(`Cannot resolve '${e}'.`);const t=window.document.createElement("a");return t.href=e,this._logger.log(At.Information,`Normalizing '${e}' to '${t.href}'.`),t.href}_resolveNegotiateUrl(e){const t=new URL(e);t.pathname.endsWith("/")?t.pathname+="negotiate":t.pathname+="/negotiate";const n=new URLSearchParams(t.searchParams);return n.has("negotiateVersion")||n.append("negotiateVersion",this._negotiateVersion.toString()),n.has("useStatefulReconnect")?"true"===n.get("useStatefulReconnect")&&(this._options._useStatefulReconnect=!0):!0===this._options._useStatefulReconnect&&n.append("useStatefulReconnect","true"),t.search=n.toString(),t.toString()}}class In{constructor(e){this._transport=e,this._buffer=[],this._executing=!0,this._sendBufferedData=new kn,this._transportResult=new kn,this._sendLoopPromise=this._sendLoop()}send(e){return this._bufferData(e),this._transportResult||(this._transportResult=new kn),this._transportResult.promise}stop(){return this._executing=!1,this._sendBufferedData.resolve(),this._sendLoopPromise}_bufferData(e){if(this._buffer.length&&typeof this._buffer[0]!=typeof e)throw new Error(`Expected data to be of type ${typeof this._buffer} but was of type ${typeof e}`);this._buffer.push(e),this._sendBufferedData.resolve()}async _sendLoop(){for(;;){if(await this._sendBufferedData.promise,!this._executing){this._transportResult&&this._transportResult.reject("Connection stopped.");break}this._sendBufferedData=new kn;const e=this._transportResult;this._transportResult=void 0;const t="string"==typeof this._buffer[0]?this._buffer.join(""):In._concatBuffers(this._buffer);this._buffer.length=0;try{await this._transport.send(t),e.resolve()}catch(t){e.reject(t)}}}static _concatBuffers(e){const t=e.map((e=>e.byteLength)).reduce(((e,t)=>e+t)),n=new Uint8Array(t);let o=0;for(const t of e)n.set(new Uint8Array(t),o),o+=t.byteLength;return n.buffer}}class kn{constructor(){this.promise=new Promise(((e,t)=>[this._resolver,this._rejecter]=[e,t]))}resolve(){this._resolver()}reject(e){this._rejecter(e)}}class Tn{constructor(){this.name="json",this.version=2,this.transferFormat=wn.Text}parseMessages(e,t){if("string"!=typeof e)throw new Error("Invalid input for JSON hub protocol. Expected a string.");if(!e)return[];null===t&&(t=Nt.instance);const n=xt.parse(e),o=[];for(const e of n){const n=JSON.parse(e);if("number"!=typeof n.type)throw new Error("Invalid payload.");switch(n.type){case tn.Invocation:this._isInvocationMessage(n);break;case tn.StreamItem:this._isStreamItemMessage(n);break;case tn.Completion:this._isCompletionMessage(n);break;case tn.Ping:case tn.Close:break;case tn.Ack:this._isAckMessage(n);break;case tn.Sequence:this._isSequenceMessage(n);break;default:t.log(At.Information,"Unknown message type '"+n.type+"' ignored.");continue}o.push(n)}return o}writeMessage(e){return xt.write(JSON.stringify(e))}_isInvocationMessage(e){this._assertNotEmptyString(e.target,"Invalid payload for Invocation message."),void 0!==e.invocationId&&this._assertNotEmptyString(e.invocationId,"Invalid payload for Invocation message.")}_isStreamItemMessage(e){if(this._assertNotEmptyString(e.invocationId,"Invalid payload for StreamItem message."),void 0===e.item)throw new Error("Invalid payload for StreamItem message.")}_isCompletionMessage(e){if(e.result&&e.error)throw new Error("Invalid payload for Completion message.");!e.result&&e.error&&this._assertNotEmptyString(e.error,"Invalid payload for Completion message."),this._assertNotEmptyString(e.invocationId,"Invalid payload for Completion message.")}_isAckMessage(e){if("number"!=typeof e.sequenceId)throw new Error("Invalid SequenceId for Ack message.")}_isSequenceMessage(e){if("number"!=typeof e.sequenceId)throw new Error("Invalid SequenceId for Sequence message.")}_assertNotEmptyString(e,t){if("string"!=typeof e||""===e)throw new Error(t)}}const Dn={trace:At.Trace,debug:At.Debug,info:At.Information,information:At.Information,warn:At.Warning,warning:At.Warning,error:At.Error,critical:At.Critical,none:At.None};class Rn{configureLogging(e){if(Pt.isRequired(e,"logging"),function(e){return void 0!==e.log}(e))this.logger=e;else if("string"==typeof e){const t=function(e){const t=Dn[e.toLowerCase()];if(void 0!==t)return t;throw new Error(`Unknown log level: ${e}`)}(e);this.logger=new $t(t)}else this.logger=new $t(e);return this}withUrl(e,t){return Pt.isRequired(e,"url"),Pt.isNotEmpty(e,"url"),this.url=e,this.httpConnectionOptions="object"==typeof t?{...this.httpConnectionOptions,...t}:{...this.httpConnectionOptions,transport:t},this}withHubProtocol(e){return Pt.isRequired(e,"protocol"),this.protocol=e,this}withAutomaticReconnect(e){if(this.reconnectPolicy)throw new Error("A reconnectPolicy has already been set.");return e?Array.isArray(e)?this.reconnectPolicy=new ln(e):this.reconnectPolicy=e:this.reconnectPolicy=new ln,this}withServerTimeout(e){return Pt.isRequired(e,"milliseconds"),this._serverTimeoutInMilliseconds=e,this}withKeepAliveInterval(e){return Pt.isRequired(e,"milliseconds"),this._keepAliveIntervalInMilliseconds=e,this}withStatefulReconnect(e){return void 0===this.httpConnectionOptions&&(this.httpConnectionOptions={}),this.httpConnectionOptions._useStatefulReconnect=!0,this._statefulReconnectBufferSize=null==e?void 0:e.bufferSize,this}build(){const e=this.httpConnectionOptions||{};if(void 0===e.logger&&(e.logger=this.logger),!this.url)throw new Error("The 'HubConnectionBuilder.withUrl' method must be called before building the connection.");const t=new Cn(this.url,e);return an.create(t,this.logger||Nt.instance,this.protocol||new Tn,this.reconnectPolicy,this._serverTimeoutInMilliseconds,this._keepAliveIntervalInMilliseconds,this._statefulReconnectBufferSize)}}var xn;!function(e){e[e.Default=0]="Default",e[e.Server=1]="Server",e[e.WebAssembly=2]="WebAssembly",e[e.WebView=3]="WebView"}(xn||(xn={}));var An,Nn,Mn,Pn=4294967295;function Un(e,t,n){var o=Math.floor(n/4294967296),r=n;e.setUint32(t,o),e.setUint32(t+4,r)}function Ln(e,t){return 4294967296*e.getInt32(t)+e.getUint32(t+4)}var Bn=("undefined"==typeof process||"never"!==(null===(An=null===process||void 0===process?void 0:process.env)||void 0===An?void 0:An.TEXT_ENCODING))&&"undefined"!=typeof TextEncoder&&"undefined"!=typeof TextDecoder;function Fn(e){for(var t=e.length,n=0,o=0;o=55296&&r<=56319&&o65535&&(h-=65536,i.push(h>>>10&1023|55296),h=56320|1023&h),i.push(h)}else i.push(a);i.length>=4096&&(s+=String.fromCharCode.apply(String,i),i.length=0)}return i.length>0&&(s+=String.fromCharCode.apply(String,i)),s}var Wn,qn=Bn?new TextDecoder:null,zn=Bn?"undefined"!=typeof process&&"force"!==(null===(Mn=null===process||void 0===process?void 0:process.env)||void 0===Mn?void 0:Mn.TEXT_DECODER)?200:0:Pn,Jn=function(e,t){this.type=e,this.data=t},Kn=(Wn=function(e,t){return Wn=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},Wn(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function n(){this.constructor=e}Wn(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),Vn=function(e){function t(n){var o=e.call(this,n)||this,r=Object.create(t.prototype);return Object.setPrototypeOf(o,r),Object.defineProperty(o,"name",{configurable:!0,enumerable:!1,value:t.name}),o}return Kn(t,e),t}(Error),Xn={type:-1,encode:function(e){var t,n,o,r;return e instanceof Date?function(e){var t,n=e.sec,o=e.nsec;if(n>=0&&o>=0&&n<=17179869183){if(0===o&&n<=4294967295){var r=new Uint8Array(4);return(t=new DataView(r.buffer)).setUint32(0,n),r}var i=n/4294967296,s=4294967295&n;return r=new Uint8Array(8),(t=new DataView(r.buffer)).setUint32(0,o<<2|3&i),t.setUint32(4,s),r}return r=new Uint8Array(12),(t=new DataView(r.buffer)).setUint32(0,o),Un(t,4,n),r}((o=1e6*((t=e.getTime())-1e3*(n=Math.floor(t/1e3))),{sec:n+(r=Math.floor(o/1e9)),nsec:o-1e9*r})):null},decode:function(e){var t=function(e){var t=new DataView(e.buffer,e.byteOffset,e.byteLength);switch(e.byteLength){case 4:return{sec:t.getUint32(0),nsec:0};case 8:var n=t.getUint32(0);return{sec:4294967296*(3&n)+t.getUint32(4),nsec:n>>>2};case 12:return{sec:Ln(t,4),nsec:t.getUint32(0)};default:throw new Vn("Unrecognized data size for timestamp (expected 4, 8, or 12): ".concat(e.length))}}(e);return new Date(1e3*t.sec+t.nsec/1e6)}},Gn=function(){function e(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(Xn)}return e.prototype.register=function(e){var t=e.type,n=e.encode,o=e.decode;if(t>=0)this.encoders[t]=n,this.decoders[t]=o;else{var r=1+t;this.builtInEncoders[r]=n,this.builtInDecoders[r]=o}},e.prototype.tryToEncode=function(e,t){for(var n=0;nthis.maxDepth)throw new Error("Too deep objects in depth ".concat(t));null==e?this.encodeNil():"boolean"==typeof e?this.encodeBoolean(e):"number"==typeof e?this.encodeNumber(e):"string"==typeof e?this.encodeString(e):this.encodeObject(e,t)},e.prototype.ensureBufferSizeToWrite=function(e){var t=this.pos+e;this.view.byteLength=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):(this.writeU8(211),this.writeI64(e)):this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))},e.prototype.writeStringHeader=function(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else{if(!(e<4294967296))throw new Error("Too long string: ".concat(e," bytes in UTF-8"));this.writeU8(219),this.writeU32(e)}},e.prototype.encodeString=function(e){if(e.length>$n){var t=Fn(e);this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),Hn(e,this.bytes,this.pos),this.pos+=t}else t=Fn(e),this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),function(e,t,n){for(var o=e.length,r=n,i=0;i>6&31|192;else{if(s>=55296&&s<=56319&&i>12&15|224,t[r++]=s>>6&63|128):(t[r++]=s>>18&7|240,t[r++]=s>>12&63|128,t[r++]=s>>6&63|128)}t[r++]=63&s|128}else t[r++]=s}}(e,this.bytes,this.pos),this.pos+=t},e.prototype.encodeObject=function(e,t){var n=this.extensionCodec.tryToEncode(e,this.context);if(null!=n)this.encodeExtension(n);else if(Array.isArray(e))this.encodeArray(e,t);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else{if("object"!=typeof e)throw new Error("Unrecognized object: ".concat(Object.prototype.toString.apply(e)));this.encodeMap(e,t)}},e.prototype.encodeBinary=function(e){var t=e.byteLength;if(t<256)this.writeU8(196),this.writeU8(t);else if(t<65536)this.writeU8(197),this.writeU16(t);else{if(!(t<4294967296))throw new Error("Too large binary: ".concat(t));this.writeU8(198),this.writeU32(t)}var n=Yn(e);this.writeU8a(n)},e.prototype.encodeArray=function(e,t){var n=e.length;if(n<16)this.writeU8(144+n);else if(n<65536)this.writeU8(220),this.writeU16(n);else{if(!(n<4294967296))throw new Error("Too large array: ".concat(n));this.writeU8(221),this.writeU32(n)}for(var o=0,r=e;o0&&e<=this.maxKeyLength},e.prototype.find=function(e,t,n){e:for(var o=0,r=this.caches[n-1];o=this.maxLengthPerKey?n[Math.random()*n.length|0]=o:n.push(o)},e.prototype.decode=function(e,t,n){var o=this.find(e,t,n);if(null!=o)return this.hit++,o;this.miss++;var r=jn(e,t,n),i=Uint8Array.prototype.slice.call(e,t,t+n);return this.store(i,r),r},e}(),to=function(e,t){var n,o,r,i,s={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return i={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(i){return function(a){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,o&&(r=2&i[0]?o.return:i[0]?o.throw||((r=o.return)&&r.call(o),0):o.next)&&!(r=r.call(o,i[1])).done)return r;switch(o=0,r&&(i=[2&i[0],r.value]),i[0]){case 0:case 1:r=i;break;case 4:return s.label++,{value:i[1],done:!1};case 5:s.label++,o=i[1],i=[0];continue;case 7:i=s.ops.pop(),s.trys.pop();continue;default:if(!((r=(r=s.trys).length>0&&r[r.length-1])||6!==i[0]&&2!==i[0])){s=0;continue}if(3===i[0]&&(!r||i[1]>r[0]&&i[1]=e},e.prototype.createExtraByteError=function(e){var t=this.view,n=this.pos;return new RangeError("Extra ".concat(t.byteLength-n," of ").concat(t.byteLength," byte(s) found at buffer[").concat(e,"]"))},e.prototype.decode=function(e){this.reinitializeState(),this.setBuffer(e);var t=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return t},e.prototype.decodeMulti=function(e){return to(this,(function(t){switch(t.label){case 0:this.reinitializeState(),this.setBuffer(e),t.label=1;case 1:return this.hasRemaining(1)?[4,this.doDecodeSync()]:[3,3];case 2:return t.sent(),[3,1];case 3:return[2]}}))},e.prototype.decodeAsync=function(e){var t,n,o,r,i,s,a;return i=this,void 0,a=function(){var i,s,a,c,l,h,d,u;return to(this,(function(p){switch(p.label){case 0:i=!1,p.label=1;case 1:p.trys.push([1,6,7,12]),t=no(e),p.label=2;case 2:return[4,t.next()];case 3:if((n=p.sent()).done)return[3,5];if(a=n.value,i)throw this.createExtraByteError(this.totalPos);this.appendBuffer(a);try{s=this.doDecodeSync(),i=!0}catch(e){if(!(e instanceof so))throw e}this.totalPos+=this.pos,p.label=4;case 4:return[3,2];case 5:return[3,12];case 6:return c=p.sent(),o={error:c},[3,12];case 7:return p.trys.push([7,,10,11]),n&&!n.done&&(r=t.return)?[4,r.call(t)]:[3,9];case 8:p.sent(),p.label=9;case 9:return[3,11];case 10:if(o)throw o.error;return[7];case 11:return[7];case 12:if(i){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return[2,s]}throw h=(l=this).headByte,d=l.pos,u=l.totalPos,new RangeError("Insufficient data in parsing ".concat(Zn(h)," at ").concat(u," (").concat(d," in the current buffer)"))}}))},new((s=void 0)||(s=Promise))((function(e,t){function n(e){try{r(a.next(e))}catch(e){t(e)}}function o(e){try{r(a.throw(e))}catch(e){t(e)}}function r(t){var r;t.done?e(t.value):(r=t.value,r instanceof s?r:new s((function(e){e(r)}))).then(n,o)}r((a=a.apply(i,[])).next())}))},e.prototype.decodeArrayStream=function(e){return this.decodeMultiAsync(e,!0)},e.prototype.decodeStream=function(e){return this.decodeMultiAsync(e,!1)},e.prototype.decodeMultiAsync=function(e,t){return function(n,o,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i,s=function(){var n,o,r,i,s,a,c,l,h;return to(this,(function(d){switch(d.label){case 0:n=t,o=-1,d.label=1;case 1:d.trys.push([1,13,14,19]),r=no(e),d.label=2;case 2:return[4,oo(r.next())];case 3:if((i=d.sent()).done)return[3,12];if(s=i.value,t&&0===o)throw this.createExtraByteError(this.totalPos);this.appendBuffer(s),n&&(o=this.readArraySize(),n=!1,this.complete()),d.label=4;case 4:d.trys.push([4,9,,10]),d.label=5;case 5:return[4,oo(this.doDecodeSync())];case 6:return[4,d.sent()];case 7:return d.sent(),0==--o?[3,8]:[3,5];case 8:return[3,10];case 9:if(!((a=d.sent())instanceof so))throw a;return[3,10];case 10:this.totalPos+=this.pos,d.label=11;case 11:return[3,2];case 12:return[3,19];case 13:return c=d.sent(),l={error:c},[3,19];case 14:return d.trys.push([14,,17,18]),i&&!i.done&&(h=r.return)?[4,oo(h.call(r))]:[3,16];case 15:d.sent(),d.label=16;case 16:return[3,18];case 17:if(l)throw l.error;return[7];case 18:return[7];case 19:return[2]}}))}.apply(n,o||[]),a=[];return i={},c("next"),c("throw"),c("return"),i[Symbol.asyncIterator]=function(){return this},i;function c(e){s[e]&&(i[e]=function(t){return new Promise((function(n,o){a.push([e,t,n,o])>1||l(e,t)}))})}function l(e,t){try{(n=s[e](t)).value instanceof oo?Promise.resolve(n.value.v).then(h,d):u(a[0][2],n)}catch(e){u(a[0][3],e)}var n}function h(e){l("next",e)}function d(e){l("throw",e)}function u(e,t){e(t),a.shift(),a.length&&l(a[0][0],a[0][1])}}(this,arguments)},e.prototype.doDecodeSync=function(){e:for(;;){var e=this.readHeadByte(),t=void 0;if(e>=224)t=e-256;else if(e<192)if(e<128)t=e;else if(e<144){if(0!=(o=e-128)){this.pushMapState(o),this.complete();continue e}t={}}else if(e<160){if(0!=(o=e-144)){this.pushArrayState(o),this.complete();continue e}t=[]}else{var n=e-160;t=this.decodeUtf8String(n,0)}else if(192===e)t=null;else if(194===e)t=!1;else if(195===e)t=!0;else if(202===e)t=this.readF32();else if(203===e)t=this.readF64();else if(204===e)t=this.readU8();else if(205===e)t=this.readU16();else if(206===e)t=this.readU32();else if(207===e)t=this.readU64();else if(208===e)t=this.readI8();else if(209===e)t=this.readI16();else if(210===e)t=this.readI32();else if(211===e)t=this.readI64();else if(217===e)n=this.lookU8(),t=this.decodeUtf8String(n,1);else if(218===e)n=this.lookU16(),t=this.decodeUtf8String(n,2);else if(219===e)n=this.lookU32(),t=this.decodeUtf8String(n,4);else if(220===e){if(0!==(o=this.readU16())){this.pushArrayState(o),this.complete();continue e}t=[]}else if(221===e){if(0!==(o=this.readU32())){this.pushArrayState(o),this.complete();continue e}t=[]}else if(222===e){if(0!==(o=this.readU16())){this.pushMapState(o),this.complete();continue e}t={}}else if(223===e){if(0!==(o=this.readU32())){this.pushMapState(o),this.complete();continue e}t={}}else if(196===e){var o=this.lookU8();t=this.decodeBinary(o,1)}else if(197===e)o=this.lookU16(),t=this.decodeBinary(o,2);else if(198===e)o=this.lookU32(),t=this.decodeBinary(o,4);else if(212===e)t=this.decodeExtension(1,0);else if(213===e)t=this.decodeExtension(2,0);else if(214===e)t=this.decodeExtension(4,0);else if(215===e)t=this.decodeExtension(8,0);else if(216===e)t=this.decodeExtension(16,0);else if(199===e)o=this.lookU8(),t=this.decodeExtension(o,1);else if(200===e)o=this.lookU16(),t=this.decodeExtension(o,2);else{if(201!==e)throw new Vn("Unrecognized type byte: ".concat(Zn(e)));o=this.lookU32(),t=this.decodeExtension(o,4)}this.complete();for(var r=this.stack;r.length>0;){var i=r[r.length-1];if(0===i.type){if(i.array[i.position]=t,i.position++,i.position!==i.size)continue e;r.pop(),t=i.array}else{if(1===i.type){if("string"!=(s=typeof t)&&"number"!==s)throw new Vn("The type of key must be string or number but "+typeof t);if("__proto__"===t)throw new Vn("The key __proto__ is not allowed");i.key=t,i.type=2;continue e}if(i.map[i.key]=t,i.readCount++,i.readCount!==i.size){i.key=null,i.type=1;continue e}r.pop(),t=i.map}}return t}var s},e.prototype.readHeadByte=function(){return-1===this.headByte&&(this.headByte=this.readU8()),this.headByte},e.prototype.complete=function(){this.headByte=-1},e.prototype.readArraySize=function(){var e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:if(e<160)return e-144;throw new Vn("Unrecognized array type byte: ".concat(Zn(e)))}},e.prototype.pushMapState=function(e){if(e>this.maxMapLength)throw new Vn("Max length exceeded: map length (".concat(e,") > maxMapLengthLength (").concat(this.maxMapLength,")"));this.stack.push({type:1,size:e,key:null,readCount:0,map:{}})},e.prototype.pushArrayState=function(e){if(e>this.maxArrayLength)throw new Vn("Max length exceeded: array length (".concat(e,") > maxArrayLength (").concat(this.maxArrayLength,")"));this.stack.push({type:0,size:e,array:new Array(e),position:0})},e.prototype.decodeUtf8String=function(e,t){var n;if(e>this.maxStrLength)throw new Vn("Max length exceeded: UTF-8 byte length (".concat(e,") > maxStrLength (").concat(this.maxStrLength,")"));if(this.bytes.byteLengthzn?function(e,t,n){var o=e.subarray(t,t+n);return qn.decode(o)}(this.bytes,r,e):jn(this.bytes,r,e),this.pos+=t+e,o},e.prototype.stateIsMapKey=function(){return this.stack.length>0&&1===this.stack[this.stack.length-1].type},e.prototype.decodeBinary=function(e,t){if(e>this.maxBinLength)throw new Vn("Max length exceeded: bin length (".concat(e,") > maxBinLength (").concat(this.maxBinLength,")"));if(!this.hasRemaining(e+t))throw ao;var n=this.pos+t,o=this.bytes.subarray(n,n+e);return this.pos+=t+e,o},e.prototype.decodeExtension=function(e,t){if(e>this.maxExtLength)throw new Vn("Max length exceeded: ext length (".concat(e,") > maxExtLength (").concat(this.maxExtLength,")"));var n=this.view.getInt8(this.pos+t),o=this.decodeBinary(e,t+1);return this.extensionCodec.decode(o,n,this.context)},e.prototype.lookU8=function(){return this.view.getUint8(this.pos)},e.prototype.lookU16=function(){return this.view.getUint16(this.pos)},e.prototype.lookU32=function(){return this.view.getUint32(this.pos)},e.prototype.readU8=function(){var e=this.view.getUint8(this.pos);return this.pos++,e},e.prototype.readI8=function(){var e=this.view.getInt8(this.pos);return this.pos++,e},e.prototype.readU16=function(){var e=this.view.getUint16(this.pos);return this.pos+=2,e},e.prototype.readI16=function(){var e=this.view.getInt16(this.pos);return this.pos+=2,e},e.prototype.readU32=function(){var e=this.view.getUint32(this.pos);return this.pos+=4,e},e.prototype.readI32=function(){var e=this.view.getInt32(this.pos);return this.pos+=4,e},e.prototype.readU64=function(){var e,t,n=(e=this.view,t=this.pos,4294967296*e.getUint32(t)+e.getUint32(t+4));return this.pos+=8,n},e.prototype.readI64=function(){var e=Ln(this.view,this.pos);return this.pos+=8,e},e.prototype.readF32=function(){var e=this.view.getFloat32(this.pos);return this.pos+=4,e},e.prototype.readF64=function(){var e=this.view.getFloat64(this.pos);return this.pos+=8,e},e}();class ho{static write(e){let t=e.byteLength||e.length;const n=[];do{let e=127&t;t>>=7,t>0&&(e|=128),n.push(e)}while(t>0);t=e.byteLength||e.length;const o=new Uint8Array(n.length+t);return o.set(n,0),o.set(e,n.length),o.buffer}static parse(e){const t=[],n=new Uint8Array(e),o=[0,7,14,21,28];for(let r=0;r7)throw new Error("Messages bigger than 2GB are not supported.");if(!(n.byteLength>=r+s+a))throw new Error("Incomplete message.");t.push(n.slice?n.slice(r+s,r+s+a):n.subarray(r+s,r+s+a)),r=r+s+a}return t}}const uo=new Uint8Array([145,tn.Ping]);class po{constructor(e){this.name="messagepack",this.version=2,this.transferFormat=wn.Binary,this._errorResult=1,this._voidResult=2,this._nonVoidResult=3,e=e||{},this._encoder=new Qn(e.extensionCodec,e.context,e.maxDepth,e.initialBufferSize,e.sortKeys,e.forceFloat32,e.ignoreUndefined,e.forceIntegerToFloat),this._decoder=new lo(e.extensionCodec,e.context,e.maxStrLength,e.maxBinLength,e.maxArrayLength,e.maxMapLength,e.maxExtLength)}parseMessages(e,t){if(!(n=e)||"undefined"==typeof ArrayBuffer||!(n instanceof ArrayBuffer||n.constructor&&"ArrayBuffer"===n.constructor.name))throw new Error("Invalid input for MessagePack hub protocol. Expected an ArrayBuffer.");var n;null===t&&(t=Nt.instance);const o=ho.parse(e),r=[];for(const e of o){const n=this._parseMessage(e,t);n&&r.push(n)}return r}writeMessage(e){switch(e.type){case tn.Invocation:return this._writeInvocation(e);case tn.StreamInvocation:return this._writeStreamInvocation(e);case tn.StreamItem:return this._writeStreamItem(e);case tn.Completion:return this._writeCompletion(e);case tn.Ping:return ho.write(uo);case tn.CancelInvocation:return this._writeCancelInvocation(e);case tn.Close:return this._writeClose();case tn.Ack:return this._writeAck(e);case tn.Sequence:return this._writeSequence(e);default:throw new Error("Invalid message type.")}}_parseMessage(e,t){if(0===e.length)throw new Error("Invalid payload.");const n=this._decoder.decode(e);if(0===n.length||!(n instanceof Array))throw new Error("Invalid payload.");const o=n[0];switch(o){case tn.Invocation:return this._createInvocationMessage(this._readHeaders(n),n);case tn.StreamItem:return this._createStreamItemMessage(this._readHeaders(n),n);case tn.Completion:return this._createCompletionMessage(this._readHeaders(n),n);case tn.Ping:return this._createPingMessage(n);case tn.Close:return this._createCloseMessage(n);case tn.Ack:return this._createAckMessage(n);case tn.Sequence:return this._createSequenceMessage(n);default:return t.log(At.Information,"Unknown message type '"+o+"' ignored."),null}}_createCloseMessage(e){if(e.length<2)throw new Error("Invalid payload for Close message.");return{allowReconnect:e.length>=3?e[2]:void 0,error:e[1],type:tn.Close}}_createPingMessage(e){if(e.length<1)throw new Error("Invalid payload for Ping message.");return{type:tn.Ping}}_createInvocationMessage(e,t){if(t.length<5)throw new Error("Invalid payload for Invocation message.");const n=t[2];return n?{arguments:t[4],headers:e,invocationId:n,streamIds:[],target:t[3],type:tn.Invocation}:{arguments:t[4],headers:e,streamIds:[],target:t[3],type:tn.Invocation}}_createStreamItemMessage(e,t){if(t.length<4)throw new Error("Invalid payload for StreamItem message.");return{headers:e,invocationId:t[2],item:t[3],type:tn.StreamItem}}_createCompletionMessage(e,t){if(t.length<4)throw new Error("Invalid payload for Completion message.");const n=t[3];if(n!==this._voidResult&&t.length<5)throw new Error("Invalid payload for Completion message.");let o,r;switch(n){case this._errorResult:o=t[4];break;case this._nonVoidResult:r=t[4]}return{error:o,headers:e,invocationId:t[2],result:r,type:tn.Completion}}_createAckMessage(e){if(e.length<1)throw new Error("Invalid payload for Ack message.");return{sequenceId:e[1],type:tn.Ack}}_createSequenceMessage(e){if(e.length<1)throw new Error("Invalid payload for Sequence message.");return{sequenceId:e[1],type:tn.Sequence}}_writeInvocation(e){let t;return t=e.streamIds?this._encoder.encode([tn.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments,e.streamIds]):this._encoder.encode([tn.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments]),ho.write(t.slice())}_writeStreamInvocation(e){let t;return t=e.streamIds?this._encoder.encode([tn.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments,e.streamIds]):this._encoder.encode([tn.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments]),ho.write(t.slice())}_writeStreamItem(e){const t=this._encoder.encode([tn.StreamItem,e.headers||{},e.invocationId,e.item]);return ho.write(t.slice())}_writeCompletion(e){const t=e.error?this._errorResult:void 0!==e.result?this._nonVoidResult:this._voidResult;let n;switch(t){case this._errorResult:n=this._encoder.encode([tn.Completion,e.headers||{},e.invocationId,t,e.error]);break;case this._voidResult:n=this._encoder.encode([tn.Completion,e.headers||{},e.invocationId,t]);break;case this._nonVoidResult:n=this._encoder.encode([tn.Completion,e.headers||{},e.invocationId,t,e.result])}return ho.write(n.slice())}_writeCancelInvocation(e){const t=this._encoder.encode([tn.CancelInvocation,e.headers||{},e.invocationId]);return ho.write(t.slice())}_writeClose(){const e=this._encoder.encode([tn.Close,null]);return ho.write(e.slice())}_writeAck(e){const t=this._encoder.encode([tn.Ack,e.sequenceId]);return ho.write(t.slice())}_writeSequence(e){const t=this._encoder.encode([tn.Sequence,e.sequenceId]);return ho.write(t.slice())}_readHeaders(e){const t=e[1];if("object"!=typeof t)throw new Error("Invalid headers.");return t}}const fo="function"==typeof TextDecoder?new TextDecoder("utf-8"):null,go=fo?fo.decode.bind(fo):function(e){let t=0;const n=e.length,o=[],r=[];for(;t65535&&(r-=65536,o.push(r>>>10&1023|55296),r=56320|1023&r),o.push(r)}o.length>1024&&(r.push(String.fromCharCode.apply(null,o)),o.length=0)}return r.push(String.fromCharCode.apply(null,o)),r.join("")},mo=Math.pow(2,32),yo=Math.pow(2,21)-1;function vo(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function wo(e,t){return e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24>>>0)}function bo(e,t){const n=wo(e,t+4);if(n>yo)throw new Error(`Cannot read uint64 with high order part ${n}, because the result would exceed Number.MAX_SAFE_INTEGER.`);return n*mo+wo(e,t)}class _o{constructor(e){this.batchData=e;const t=new Io(e);this.arrayRangeReader=new ko(e),this.arrayBuilderSegmentReader=new To(e),this.diffReader=new Eo(e),this.editReader=new So(e,t),this.frameReader=new Co(e,t)}updatedComponents(){return vo(this.batchData,this.batchData.length-20)}referenceFrames(){return vo(this.batchData,this.batchData.length-16)}disposedComponentIds(){return vo(this.batchData,this.batchData.length-12)}disposedEventHandlerIds(){return vo(this.batchData,this.batchData.length-8)}updatedComponentsEntry(e,t){const n=e+4*t;return vo(this.batchData,n)}referenceFramesEntry(e,t){return e+20*t}disposedComponentIdsEntry(e,t){const n=e+4*t;return vo(this.batchData,n)}disposedEventHandlerIdsEntry(e,t){const n=e+8*t;return bo(this.batchData,n)}}class Eo{constructor(e){this.batchDataUint8=e}componentId(e){return vo(this.batchDataUint8,e)}edits(e){return e+4}editsEntry(e,t){return e+16*t}}class So{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}editType(e){return vo(this.batchDataUint8,e)}siblingIndex(e){return vo(this.batchDataUint8,e+4)}newTreeIndex(e){return vo(this.batchDataUint8,e+8)}moveToSiblingIndex(e){return vo(this.batchDataUint8,e+8)}removedAttributeName(e){const t=vo(this.batchDataUint8,e+12);return this.stringReader.readString(t)}}class Co{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}frameType(e){return vo(this.batchDataUint8,e)}subtreeLength(e){return vo(this.batchDataUint8,e+4)}elementReferenceCaptureId(e){const t=vo(this.batchDataUint8,e+4);return this.stringReader.readString(t)}componentId(e){return vo(this.batchDataUint8,e+8)}elementName(e){const t=vo(this.batchDataUint8,e+8);return this.stringReader.readString(t)}textContent(e){const t=vo(this.batchDataUint8,e+4);return this.stringReader.readString(t)}markupContent(e){const t=vo(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeName(e){const t=vo(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeValue(e){const t=vo(this.batchDataUint8,e+8);return this.stringReader.readString(t)}attributeEventHandlerId(e){return bo(this.batchDataUint8,e+12)}}class Io{constructor(e){this.batchDataUint8=e,this.stringTableStartIndex=vo(e,e.length-4)}readString(e){if(-1===e)return null;{const n=vo(this.batchDataUint8,this.stringTableStartIndex+4*e),o=function(e,t){let n=0,o=0;for(let r=0;r<4;r++){const i=e[t+r];if(n|=(127&i)<this.nextBatchId)return this.fatalError?(this.logger.log(ft.Debug,`Received a new batch ${e} but errored out on a previous batch ${this.nextBatchId-1}`),void await n.send("OnRenderCompleted",this.nextBatchId-1,this.fatalError.toString())):void this.logger.log(ft.Debug,`Waiting for batch ${this.nextBatchId}. Batch ${e} not processed.`);try{this.nextBatchId++,this.logger.log(ft.Debug,`Applying batch ${e}.`),Ce(xn.Server,new _o(t)),await this.completeBatch(n,e)}catch(t){throw this.fatalError=t.toString(),this.logger.log(ft.Error,`There was an error applying batch ${e}.`),n.send("OnRenderCompleted",e,t.toString()),t}}getLastBatchid(){return this.nextBatchId-1}async completeBatch(e,t){try{await e.send("OnRenderCompleted",t,null)}catch{this.logger.log(ft.Warning,`Failed to deliver completion notification for render '${t}'.`)}}}let Ro=!1;function xo(){const e=document.querySelector("#blazor-error-ui");e&&(e.style.display="block"),Ro||(Ro=!0,document.querySelectorAll("#blazor-error-ui .reload").forEach((e=>{e.onclick=function(e){location.reload(),e.preventDefault()}})),document.querySelectorAll("#blazor-error-ui .dismiss").forEach((e=>{e.onclick=function(e){const t=document.querySelector("#blazor-error-ui");t&&(t.style.display="none"),e.preventDefault()}})))}class Ao{constructor(t,n,o,r){this._renderingFailed=!1,this._disposed=!1,this._circuitId=void 0,this._applicationState=n,this._componentManager=t,this._options=o,this._logger=r,this._renderQueue=new Do(this._logger),this._dispatcher=e.attachDispatcher(this)}start(){if(this.isDisposedOrDisposing())throw new Error("Cannot start a disposed circuit.");return this._startPromise||(this._startPromise=this.startCore()),this._startPromise}async startCore(){if(this._connection=await this.startConnection(),this._connection.state!==nn.Connected)return!1;const e=JSON.stringify(this._componentManager.initialComponents.map((e=>Dt(e))));return this._circuitId=await this._connection.invoke("StartCircuit",We.getBaseURI(),We.getLocationHref(),e,this._applicationState||""),!!this._circuitId}async startConnection(){var e,t;const n=new po;n.name="blazorpack";const o=(new Rn).withUrl("_blazor").withHubProtocol(n);this._options.configureSignalR(o);const r=o.build();r.on("JS.AttachComponent",((e,t)=>Ee(xn.Server,this.resolveElement(t,e),e,!1))),r.on("JS.BeginInvokeJS",this._dispatcher.beginInvokeJSFromDotNet.bind(this._dispatcher)),r.on("JS.EndInvokeDotNet",this._dispatcher.endInvokeDotNetFromJS.bind(this._dispatcher)),r.on("JS.ReceiveByteArray",this._dispatcher.receiveByteArray.bind(this._dispatcher)),r.on("JS.BeginTransmitStream",(e=>{const t=new ReadableStream({start:t=>{r.stream("SendDotNetStreamToJS",e).subscribe({next:e=>t.enqueue(e),complete:()=>t.close(),error:e=>t.error(e)})}});this._dispatcher.supplyDotNetStream(e,t)})),r.on("JS.RenderBatch",(async(e,t)=>{var n,o;this._logger.log(At.Debug,`Received render batch with id ${e} and ${t.byteLength} bytes.`),await this._renderQueue.processBatch(e,t,this._connection),null===(o=(n=this._componentManager).onAfterRenderBatch)||void 0===o||o.call(n,xn.Server)})),r.on("JS.EndLocationChanging",pt._internal.navigationManager.endLocationChanging),r.onclose((e=>!this._disposed&&!this._renderingFailed&&this._options.reconnectionHandler.onConnectionDown(this._options.reconnectionOptions,e))),r.on("JS.Error",(e=>{this._renderingFailed=!0,this.unhandledError(e),xo()}));try{await r.start()}catch(e){if(this.unhandledError(e),"FailedToNegotiateWithServerError"===e.errorType)throw e;xo(),e.innerErrors&&(e.innerErrors.some((e=>"UnsupportedTransportError"===e.errorType&&e.transport===vn.WebSockets))?this._logger.log(At.Error,"Unable to connect, please ensure you are using an updated browser that supports WebSockets."):e.innerErrors.some((e=>"FailedToStartTransportError"===e.errorType&&e.transport===vn.WebSockets))?this._logger.log(At.Error,"Unable to connect, please ensure WebSockets are available. A VPN or proxy may be blocking the connection."):e.innerErrors.some((e=>"DisabledTransportError"===e.errorType&&e.transport===vn.LongPolling))&&this._logger.log(At.Error,"Unable to initiate a SignalR connection to the server. This might be because the server is not configured to support WebSockets. For additional details, visit https://aka.ms/blazor-server-websockets-error."))}return(null===(t=null===(e=r.connection)||void 0===e?void 0:e.features)||void 0===t?void 0:t.inherentKeepAlive)&&this._logger.log(At.Warning,"Failed to connect via WebSockets, using the Long Polling fallback transport. This may be due to a VPN or proxy blocking the connection. To troubleshoot this, visit https://aka.ms/blazor-server-using-fallback-long-polling."),r}async disconnect(){var e;await(null===(e=this._connection)||void 0===e?void 0:e.stop())}async reconnect(){if(!this._circuitId)throw new Error("Circuit host not initialized.");return this._connection.state===nn.Connected||(this._connection=await this.startConnection(),!!await this._connection.invoke("ConnectCircuit",this._circuitId)&&(this._options.reconnectionHandler.onConnectionUp(),!0))}beginInvokeDotNetFromJS(e,t,n,o,r){this.throwIfDispatchingWhenDisposed(),this._connection.send("BeginInvokeDotNetFromJS",e?e.toString():null,t,n,o||0,r)}endInvokeJSFromDotNet(e,t,n){this.throwIfDispatchingWhenDisposed(),this._connection.send("EndInvokeJSFromDotNet",e,t,n)}sendByteArray(e,t){this.throwIfDispatchingWhenDisposed(),this._connection.send("ReceiveByteArray",e,t)}throwIfDispatchingWhenDisposed(){if(this._disposed)throw new Error("The circuit associated with this dispatcher is no longer available.")}sendLocationChanged(e,t,n){return this._connection.send("OnLocationChanged",e,t,n)}sendLocationChanging(e,t,n,o){return this._connection.send("OnLocationChanging",e,t,n,o)}sendJsDataStream(e,t,n){return function(e,t,n,o){setTimeout((async()=>{let r=5,i=(new Date).valueOf();try{const s=t instanceof Blob?t.size:t.byteLength;let a=0,c=0;for(;a1)await e.send("ReceiveJSDataChunk",n,c,h,null);else{if(!await e.invoke("ReceiveJSDataChunk",n,c,h,null))break;const t=(new Date).valueOf(),o=t-i;i=t,r=Math.max(1,Math.round(500/Math.max(1,o)))}a+=l,c++}}catch(t){await e.send("ReceiveJSDataChunk",n,-1,null,t.toString())}}),0)}(this._connection,e,t,n)}resolveElement(e,t){const n=w(e);if(n)return H(n,!0);const o=Number.parseInt(e);if(!Number.isNaN(o))return $(this._componentManager.resolveRootComponent(o,t));throw new Error(`Invalid sequence number or identifier '${e}'.`)}getRootComponentManager(){return this._componentManager}unhandledError(e){this._logger.log(At.Error,e),this.disconnect()}getDisconnectFormData(){const e=new FormData,t=this._circuitId;return e.append("circuitId",t),e}didRenderingFail(){return this._renderingFailed}isDisposedOrDisposing(){return void 0!==this._disposePromise}sendDisconnectBeacon(){if(this._disposed)return;const e=this.getDisconnectFormData();this._disposed=navigator.sendBeacon("_blazor/disconnect",e)}dispose(){return this._disposePromise||(this._disposePromise=this.disposeCore()),this._disposePromise}async disposeCore(){var e;if(!this._startPromise)return void(this._disposed=!0);await this._startPromise,this._disposed=!0,null===(e=this._connection)||void 0===e||e.stop();const t=this.getDisconnectFormData();fetch("_blazor/disconnect",{method:"POST",body:t}),function(e){if(!S.delete(e))throw new Error(`Interop methods are not registered for renderer ${e}`)}(xn.Server)}}const No={configureSignalR:e=>{},logLevel:ft.Warning,reconnectionOptions:{maxRetries:8,retryIntervalMilliseconds:2e4,dialogId:"components-reconnect-modal"}};class Mo{constructor(e,t,n,o){this.maxRetries=t,this.document=n,this.logger=o,this.addedToDom=!1,this.modal=this.document.createElement("div"),this.modal.id=e,this.maxRetries=t,this.modal.style.cssText=["position: fixed","top: 0","right: 0","bottom: 0","left: 0","z-index: 1050","display: none","overflow: hidden","background-color: #fff","opacity: 0.8","text-align: center","font-weight: bold","transition: visibility 0s linear 500ms"].join(";"),this.message=this.document.createElement("h5"),this.message.style.cssText="margin-top: 20px",this.button=this.document.createElement("button"),this.button.style.cssText="margin:5px auto 5px",this.button.textContent="Retry";const r=this.document.createElement("a");r.addEventListener("click",(()=>location.reload())),r.textContent="reload",this.reloadParagraph=this.document.createElement("p"),this.reloadParagraph.textContent="Alternatively, ",this.reloadParagraph.appendChild(r),this.modal.appendChild(this.message),this.modal.appendChild(this.button),this.modal.appendChild(this.reloadParagraph),this.loader=this.getLoader(),this.message.after(this.loader),this.button.addEventListener("click",(async()=>{this.show();try{await pt.reconnect()||this.rejected()}catch(e){this.logger.log(ft.Error,e),this.failed()}}))}show(){this.addedToDom||(this.addedToDom=!0,this.document.body.appendChild(this.modal)),this.modal.style.display="block",this.loader.style.display="inline-block",this.button.style.display="none",this.reloadParagraph.style.display="none",this.message.textContent="Attempting to reconnect to the server...",this.modal.style.visibility="hidden",setTimeout((()=>{this.modal.style.visibility="visible"}),0)}update(e){this.message.textContent=`Attempting to reconnect to the server: ${e} of ${this.maxRetries}`}hide(){this.modal.style.display="none"}failed(){this.button.style.display="block",this.reloadParagraph.style.display="none",this.loader.style.display="none";const e=this.document.createTextNode("Reconnection failed. Try "),t=this.document.createElement("a");t.textContent="reloading",t.setAttribute("href",""),t.addEventListener("click",(()=>location.reload()));const n=this.document.createTextNode(" the page if you're unable to reconnect.");this.message.replaceChildren(e,t,n)}rejected(){this.button.style.display="none",this.reloadParagraph.style.display="none",this.loader.style.display="none";const e=this.document.createTextNode("Could not reconnect to the server. "),t=this.document.createElement("a");t.textContent="Reload",t.setAttribute("href",""),t.addEventListener("click",(()=>location.reload()));const n=this.document.createTextNode(" the page to restore functionality.");this.message.replaceChildren(e,t,n)}getLoader(){const e=this.document.createElement("div");return e.style.cssText=["border: 0.3em solid #f3f3f3","border-top: 0.3em solid #3498db","border-radius: 50%","width: 2em","height: 2em","display: inline-block"].join(";"),e.animate([{transform:"rotate(0deg)"},{transform:"rotate(360deg)"}],{duration:2e3,iterations:1/0}),e}}class Po{constructor(e,t,n){this.dialog=e,this.maxRetries=t,this.document=n,this.document=n;const o=this.document.getElementById(Po.MaxRetriesId);o&&(o.innerText=this.maxRetries.toString())}show(){this.removeClasses(),this.dialog.classList.add(Po.ShowClassName)}update(e){const t=this.document.getElementById(Po.CurrentAttemptId);t&&(t.innerText=e.toString())}hide(){this.removeClasses(),this.dialog.classList.add(Po.HideClassName)}failed(){this.removeClasses(),this.dialog.classList.add(Po.FailedClassName)}rejected(){this.removeClasses(),this.dialog.classList.add(Po.RejectedClassName)}removeClasses(){this.dialog.classList.remove(Po.ShowClassName,Po.HideClassName,Po.FailedClassName,Po.RejectedClassName)}}Po.ShowClassName="components-reconnect-show",Po.HideClassName="components-reconnect-hide",Po.FailedClassName="components-reconnect-failed",Po.RejectedClassName="components-reconnect-rejected",Po.MaxRetriesId="components-reconnect-max-retries",Po.CurrentAttemptId="components-reconnect-current-attempt";class Uo{constructor(e,t,n){this._currentReconnectionProcess=null,this._logger=e,this._reconnectionDisplay=t,this._reconnectCallback=n||pt.reconnect}onConnectionDown(e,t){if(!this._reconnectionDisplay){const t=document.getElementById(e.dialogId);this._reconnectionDisplay=t?new Po(t,e.maxRetries,document):new Mo(e.dialogId,e.maxRetries,document,this._logger)}this._currentReconnectionProcess||(this._currentReconnectionProcess=new Lo(e,this._logger,this._reconnectCallback,this._reconnectionDisplay))}onConnectionUp(){this._currentReconnectionProcess&&(this._currentReconnectionProcess.dispose(),this._currentReconnectionProcess=null)}}class Lo{constructor(e,t,n,o){this.logger=t,this.reconnectCallback=n,this.isDisposed=!1,this.reconnectDisplay=o,this.reconnectDisplay.show(),this.attemptPeriodicReconnection(e)}dispose(){this.isDisposed=!0,this.reconnectDisplay.hide()}async attemptPeriodicReconnection(e){for(let t=0;tLo.MaximumFirstRetryInterval?Lo.MaximumFirstRetryInterval:e.retryIntervalMilliseconds;if(await this.delay(n),this.isDisposed)break;try{return await this.reconnectCallback()?void 0:void this.reconnectDisplay.rejected()}catch(e){this.logger.log(ft.Error,e)}}this.reconnectDisplay.failed()}delay(e){return new Promise((t=>setTimeout(t,e)))}}Lo.MaximumFirstRetryInterval=3e3;class Bo{constructor(){this.afterStartedCallbacks=[]}async importInitializersAsync(e,t){await Promise.all(e.map((e=>async function(e,n){const o=function(e){const t=document.baseURI;return t.endsWith("/")?`${t}${e}`:`${t}/${e}`}(n),r=await import(o);if(void 0===r)return;const{beforeStart:i,afterStarted:s}=r;return s&&e.afterStartedCallbacks.push(s),i?i(...t):void 0}(this,e))))}async invokeAfterStartedCallbacks(e){await k,await Promise.all(this.afterStartedCallbacks.map((t=>t(e))))}}let Fo,Oo,$o,Ho,jo,Wo=!1;function qo(e){if($o)throw new Error("Circuit options have already been configured.");$o=function(e){const t={...No,...e};return e&&e.reconnectionOptions&&(t.reconnectionOptions={...No.reconnectionOptions,...e.reconnectionOptions}),t}(e)}function zo(e){return jo=e,jo}var Jo,Ko;const Vo=navigator,Xo=Vo.userAgentData&&Vo.userAgentData.brands,Go=Xo&&Xo.length>0?Xo.some((e=>"Google Chrome"===e.brand||"Microsoft Edge"===e.brand||"Chromium"===e.brand)):window.chrome,Yo=null!==(Ko=null===(Jo=Vo.userAgentData)||void 0===Jo?void 0:Jo.platform)&&void 0!==Ko?Ko:navigator.platform;function Qo(e){return 0!==e.debugLevel&&(Go||navigator.userAgent.includes("Firefox"))}let Zo,er,tr,nr,or,rr;const ir=Math.pow(2,32),sr=Math.pow(2,21)-1;let ar=null;function cr(e){return er.getI32(e)}const lr={load:function(e,t){return async function(e,t){const{dotnet:n}=await async function(e){if("undefined"==typeof WebAssembly||!WebAssembly.validate)throw new Error("This browser does not support WebAssembly.");let t="_framework/dotnet.js";if(e.loadBootResource){const n="dotnetjs",o=e.loadBootResource(n,"dotnet.js",t,"","js-module-dotnet");if("string"==typeof o)t=o;else if(o)throw new Error(`For a ${n} resource, custom loaders must supply a URI string.`)}const n=new URL(t,document.baseURI).toString();return await import(n)}(e),o=function(e,t){const n={maxParallelDownloads:1e6,enableDownloadRetry:!1,applicationEnvironment:e.environment},o={...window.Module||{},onConfigLoaded:async(n,{invokeLibraryInitializers:o})=>{var r,i;n.environmentVariables||(n.environmentVariables={}),"sharded"===n.globalizationMode&&(n.environmentVariables.__BLAZOR_SHARDED_ICU="1"),pt._internal.getApplicationEnvironment=()=>n.applicationEnvironment,null==t||t(n);const s=[e,null!==(i=null===(r=n.resources)||void 0===r?void 0:r.extensions)&&void 0!==i?i:{}];await o("beforeStart",s)},onDownloadResourceProgress:hr,config:n,disableDotnet6Compatibility:!1,out:ur,err:pr};return o}(e,t);e.applicationCulture&&n.withApplicationCulture(e.applicationCulture),e.environment&&n.withApplicationEnvironment(e.environment),e.loadBootResource&&n.withResourceLoader(e.loadBootResource),n.withModuleConfig(o),e.configureRuntime&&e.configureRuntime(n),rr=await n.create()}(e,t)},start:function(){return async function(){if(!rr)throw new Error("The runtime must be loaded it gets configured.");const{MONO:t,BINDING:n,Module:o,setModuleImports:r,INTERNAL:i,getConfig:s,invokeLibraryInitializers:a}=rr;tr=o,Zo=n,er=t,or=i,function(e){const t=Yo.match(/^Mac/i)?"Cmd":"Alt";Qo(e)&&console.info(`Debugging hotkey: Shift+${t}+D (when application has focus)`),document.addEventListener("keydown",(t=>{t.shiftKey&&(t.metaKey||t.altKey)&&"KeyD"===t.code&&(Qo(e)?navigator.userAgent.includes("Firefox")?async function(){const e=await fetch(`_framework/debug?url=${encodeURIComponent(location.href)}&isFirefox=true`);200!==e.status&&console.warn(await e.text())}():Go?function(){const e=document.createElement("a");e.href=`_framework/debug?url=${encodeURIComponent(location.href)}`,e.target="_blank",e.rel="noopener noreferrer",e.click()}():console.error("Currently, only Microsoft Edge (80+), Google Chrome, or Chromium, are supported for debugging."):console.error("Cannot start debugging, because the application was not compiled with debugging enabled."))}))}(s()),pt.runtime=rr,pt._internal.dotNetCriticalError=pr,r("blazor-internal",{Blazor:{_internal:pt._internal}});const c=await rr.getAssemblyExports("Microsoft.AspNetCore.Components.WebAssembly");return Object.assign(pt._internal,{dotNetExports:{...c.Microsoft.AspNetCore.Components.WebAssembly.Services.DefaultWebAssemblyJSRuntime}}),nr=e.attachDispatcher({beginInvokeDotNetFromJS:(e,t,n,o,r)=>{if(gr(),!o&&!t)throw new Error("Either assemblyName or dotNetObjectId must have a non null value.");const i=o?o.toString():t;pt._internal.dotNetExports.BeginInvokeDotNet(e?e.toString():null,i,n,r)},endInvokeJSFromDotNet:(e,t,n)=>{pt._internal.dotNetExports.EndInvokeJS(n)},sendByteArray:(e,t)=>{pt._internal.dotNetExports.ReceiveByteArrayFromJS(e,t)},invokeDotNetFromJS:(e,t,n,o)=>(gr(),pt._internal.dotNetExports.InvokeDotNet(e||null,t,null!=n?n:0,o))}),{invokeLibraryInitializers:a}}()},callEntryPoint:async function(){try{await rr.runMain(rr.getConfig().mainAssemblyName,[])}catch(e){console.error(e),xo()}},toUint8Array:function(e){const t=fr(e),n=cr(t),o=new Uint8Array(n);return o.set(tr.HEAPU8.subarray(t+4,t+4+n)),o},getArrayLength:function(e){return cr(fr(e))},getArrayEntryPtr:function(e,t,n){return fr(e)+4+t*n},getObjectFieldsBaseAddress:function(e){return e+8},readInt16Field:function(e,t){return n=e+(t||0),er.getI16(n);var n},readInt32Field:function(e,t){return cr(e+(t||0))},readUint64Field:function(e,t){return function(e){const t=e>>2,n=tr.HEAPU32[t+1];if(n>sr)throw new Error(`Cannot read uint64 with high order part ${n}, because the result would exceed Number.MAX_SAFE_INTEGER.`);return n*ir+tr.HEAPU32[t]}(e+(t||0))},readFloatField:function(e,t){return n=e+(t||0),er.getF32(n);var n},readObjectField:function(e,t){return cr(e+(t||0))},readStringField:function(e,t,n){const o=cr(e+(t||0));if(0===o)return null;if(n){const e=Zo.unbox_mono_obj(o);return"boolean"==typeof e?e?"":null:e}return Zo.conv_string(o)},readStructField:function(e,t){return e+(t||0)},beginHeapLock:function(){return gr(),ar=mr.create(),ar},invokeWhenHeapUnlocked:function(e){ar?ar.enqueuePostReleaseAction(e):e()}};function hr(e,t){const n=e/t*100;document.documentElement.style.setProperty("--blazor-load-percentage",`${n}%`),document.documentElement.style.setProperty("--blazor-load-percentage-text",`"${Math.floor(n)}%"`)}const dr=["DEBUGGING ENABLED"],ur=e=>dr.indexOf(e)<0&&console.log(e),pr=e=>{console.error(e||"(null)"),xo()};function fr(e){return e+12}function gr(){if(ar)throw new Error("Assertion failed - heap is currently locked")}class mr{enqueuePostReleaseAction(e){this.postReleaseActions||(this.postReleaseActions=[]),this.postReleaseActions.push(e)}release(){var e;if(ar!==this)throw new Error("Trying to release a lock which isn't current");for(or.mono_wasm_gc_unlock(),ar=null;null===(e=this.postReleaseActions)||void 0===e?void 0:e.length;)this.postReleaseActions.shift()(),gr()}static create(){return or.mono_wasm_gc_lock(),new mr}}class yr{constructor(e){this.batchAddress=e,this.arrayRangeReader=vr,this.arrayBuilderSegmentReader=wr,this.diffReader=br,this.editReader=_r,this.frameReader=Er}updatedComponents(){return jo.readStructField(this.batchAddress,0)}referenceFrames(){return jo.readStructField(this.batchAddress,vr.structLength)}disposedComponentIds(){return jo.readStructField(this.batchAddress,2*vr.structLength)}disposedEventHandlerIds(){return jo.readStructField(this.batchAddress,3*vr.structLength)}updatedComponentsEntry(e,t){return Sr(e,t,br.structLength)}referenceFramesEntry(e,t){return Sr(e,t,Er.structLength)}disposedComponentIdsEntry(e,t){const n=Sr(e,t,4);return jo.readInt32Field(n)}disposedEventHandlerIdsEntry(e,t){const n=Sr(e,t,8);return jo.readUint64Field(n)}}const vr={structLength:8,values:e=>jo.readObjectField(e,0),count:e=>jo.readInt32Field(e,4)},wr={structLength:12,values:e=>{const t=jo.readObjectField(e,0),n=jo.getObjectFieldsBaseAddress(t);return jo.readObjectField(n,0)},offset:e=>jo.readInt32Field(e,4),count:e=>jo.readInt32Field(e,8)},br={structLength:4+wr.structLength,componentId:e=>jo.readInt32Field(e,0),edits:e=>jo.readStructField(e,4),editsEntry:(e,t)=>Sr(e,t,_r.structLength)},_r={structLength:20,editType:e=>jo.readInt32Field(e,0),siblingIndex:e=>jo.readInt32Field(e,4),newTreeIndex:e=>jo.readInt32Field(e,8),moveToSiblingIndex:e=>jo.readInt32Field(e,8),removedAttributeName:e=>jo.readStringField(e,16)},Er={structLength:36,frameType:e=>jo.readInt16Field(e,4),subtreeLength:e=>jo.readInt32Field(e,8),elementReferenceCaptureId:e=>jo.readStringField(e,16),componentId:e=>jo.readInt32Field(e,12),elementName:e=>jo.readStringField(e,16),textContent:e=>jo.readStringField(e,16),markupContent:e=>jo.readStringField(e,16),attributeName:e=>jo.readStringField(e,16),attributeValue:e=>jo.readStringField(e,24,!0),attributeEventHandlerId:e=>jo.readUint64Field(e,8)};function Sr(e,t,n){return jo.getArrayEntryPtr(e,t,n)}class Cr{constructor(e){this.componentManager=e}resolveRegisteredElement(e,t){const n=Number.parseInt(e);if(!Number.isNaN(n))return $(this.componentManager.resolveRootComponent(n,t))}getParameterValues(e){return this.componentManager.initialComponents[e].parameterValues}getParameterDefinitions(e){return this.componentManager.initialComponents[e].parameterDefinitions}getTypeName(e){return this.componentManager.initialComponents[e].typeName}getAssembly(e){return this.componentManager.initialComponents[e].assembly}getCount(){return this.componentManager.initialComponents.length}}let Ir,kr,Tr,Dr=!1,Rr=!1;const xr=new Promise((e=>{Tr=e}));function Ar(){return null!=kr||(kr=(async()=>{await lr.load(null!=Ir?Ir:{},Tr),Dr=!0})()),kr}function Nr(){return Dr}function Mr(t,n,o,r){const i=lr.readStringField(t,0),s=lr.readInt32Field(t,4),a=lr.readStringField(t,8),c=lr.readUint64Field(t,20);if(null!==a){const e=lr.readUint64Field(t,12);if(0!==e)return nr.beginInvokeJSFromDotNet(e,i,a,s,c),0;{const e=nr.invokeJSFromDotNet(i,a,s,c);return null===e?0:Zo.js_string_to_mono_string(e)}}{const t=e.findJSFunction(i,c).call(null,n,o,r);switch(s){case e.JSCallResultType.Default:return t;case e.JSCallResultType.JSObjectReference:return e.createJSObjectReference(t).__jsObjectId;case e.JSCallResultType.JSStreamReference:{const n=e.createJSStreamReference(t),o=JSON.stringify(n);return Zo.js_string_to_mono_string(o)}case e.JSCallResultType.JSVoidResult:return null;default:throw new Error(`Invalid JS call result type '${s}'.`)}}}function Pr(e,t,n,o,r){return 0!==r?(nr.beginInvokeJSFromDotNet(r,e,o,n,t),null):nr.invokeJSFromDotNet(e,o,n,t)}function Ur(e,t,n){nr.endInvokeDotNetFromJS(e,t,n)}function Lr(e,t,n,o){!function(e,t,n,o,r){let i=ut.get(t);if(!i){const n=new ReadableStream({start(e){ut.set(t,e),i=e}});e.supplyDotNetStream(t,n)}r?(i.error(r),ut.delete(t)):0===o?(i.close(),ut.delete(t)):i.enqueue(n.length===o?n:n.subarray(0,o))}(nr,e,t,n,o)}function Br(e,t){nr.receiveByteArray(e,t)}function Fr(e,t){t.namespaceURI?e.setAttributeNS(t.namespaceURI,t.name,t.value):e.setAttribute(t.name,t.value)}const Or="data-permanent";var $r,Hr;!function(e){e[e.None=0]="None",e[e.Some=1]="Some",e[e.Infinite=2]="Infinite"}($r||($r={})),function(e){e.Keep="keep",e.Update="update",e.Insert="insert",e.Delete="delete"}(Hr||(Hr={}));class jr{static create(e,t,n){return 0===t&&n===e.length?e:new jr(e,t,n)}constructor(e,t,n){this.source=e,this.startIndex=t,this.length=n}item(e){return this.source.item(e+this.startIndex)}forEach(e,t){for(let t=0;t=n&&s>=o&&r(e.item(i),t.item(s))===$r.None;)i--,s--,a++;return a}(e,t,o,o,n),i=function(e){var t;const n=[];let o=e.length-1,r=(null===(t=e[o])||void 0===t?void 0:t.length)-1;for(;o>0||r>0;){const t=0===o?Hr.Insert:0===r?Hr.Delete:e[o][r];switch(n.unshift(t),t){case Hr.Keep:case Hr.Update:o--,r--;break;case Hr.Insert:r--;break;case Hr.Delete:o--}}return n}(function(e,t,n){const o=[],r=[],i=e.length,s=t.length;if(0===i&&0===s)return[];for(let e=0;e<=i;e++)(o[e]=Array(s+1))[0]=e,r[e]=Array(s+1);const a=o[0];for(let e=1;e<=s;e++)a[e]=e;for(let a=1;a<=i;a++)for(let i=1;i<=s;i++){const s=n(e.item(a-1),t.item(i-1)),c=o[a-1][i]+1,l=o[a][i-1]+1;let h;switch(s){case $r.None:h=o[a-1][i-1];break;case $r.Some:h=o[a-1][i-1]+1;break;case $r.Infinite:h=Number.MAX_VALUE}h{history.pushState(null,"",e),li(e)}))}function ai(e){Pe()||li(location.href)}function ci(e){if(Pe()||e.defaultPrevented)return;const t=e.target;if(t instanceof HTMLFormElement){if(!function(e){const t=e.getAttribute("data-enhance");return"string"==typeof t&&""===t||"true"===(null==t?void 0:t.toLowerCase())}(t))return;e.preventDefault();const n=new URL(t.action),o={method:t.method},r=new FormData(t),i=e.submitter;i&&i.name&&r.append(i.name,i.value),"get"===o.method?n.search=new URLSearchParams(r).toString():o.body=r,li(n.toString(),o)}}async function li(e,t){zr=!0,null==Wr||Wr.abort(),Wr=new AbortController;const n=Wr.signal,o=fetch(e,Object.assign({signal:n,mode:"no-cors",headers:{accept:"text/html;blazor-enhanced-nav=on"}},t));if(await async function(e,t,n,o){let r;try{if(r=await e,!r.body)return void n(r,"");const t=r.headers.get("ssr-framing");if(!t){const e=await r.text();return void n(r,e)}let o=!0;await r.body.pipeThrough(new TextDecoderStream).pipeThrough(function(e){let t="";return new TransformStream({transform(n,o){if(t+=n,t.indexOf(e,t.length-n.length-e.length)>=0){const n=t.split(e);n.slice(0,-1).forEach((e=>o.enqueue(e))),t=n[n.length-1]}},flush(e){e.enqueue(t)}})}(`\x3c!--${t}--\x3e`)).pipeTo(new WritableStream({write(e){o?(o=!1,n(r,e)):(e=>{const t=document.createRange().createContextualFragment(e);for(;t.firstChild;)document.body.appendChild(t.firstChild)})(e)}}))}catch(e){if("AbortError"===e.name&&t.aborted)return;throw e}}(o,n,((n,o)=>{const r=!(null==t?void 0:t.method)||"get"===t.method,i=n.status>=200&&n.status<300;if("opaque"===n.type){if(r)return void di(e);throw new Error("Enhanced navigation does not support making a non-GET request to an endpoint that redirects to an external origin. Avoid enabling enhanced navigation for form posts that may perform external redirections.")}if(i&&"allow"!==n.headers.get("blazor-enhanced-nav")){if(r)return void di(e);throw new Error("Enhanced navigation does not support making a non-GET request to a non-Blazor endpoint. Avoid enabling enhanced navigation for forms that post to a non-Blazor endpoint.")}n.redirected&&(r?history.replaceState(null,"",n.url):history.pushState(null,"",n.url),e=n.url);const s=n.headers.get("blazor-enhanced-nav-redirect-location");if(s)return void location.replace(s);const a=n.headers.get("content-type");if((null==a?void 0:a.startsWith("text/html"))&&o){const e=(new DOMParser).parseFromString(o,"text/html");Kr(document,e),qr.documentUpdated()}else(null==a?void 0:a.startsWith("text/"))&&o?hi(o):i||o?r?di(e):hi(`Error: ${t.method} request to ${e} returned non-HTML content of type ${a||"unspecified"}.`):hi(`Error: ${n.status} ${n.statusText}`)})),!n.aborted){const t=e.indexOf("#");if(t>=0){const n=e.substring(t+1),o=document.getElementById(n);null==o||o.scrollIntoView()}zr=!1,qr.enhancedNavigationCompleted()}}function hi(e){document.documentElement.textContent=e;const t=document.documentElement.style;t.fontFamily="consolas, monospace",t.whiteSpace="pre-wrap",t.padding="1rem"}function di(e){history.replaceState(null,"",e+"?"),location.replace(e)}let ui,pi=!0;class fi extends HTMLElement{connectedCallback(){var e;const t=this.parentNode;null===(e=t.parentNode)||void 0===e||e.removeChild(t),t.childNodes.forEach((e=>{if(e instanceof HTMLTemplateElement){const t=e.getAttribute("blazor-component-id");if(t)!function(e,t){const n=function(e){const t=`bl:${e}`,n=document.createNodeIterator(document,NodeFilter.SHOW_COMMENT);let o=null;for(;(o=n.nextNode())&&o.textContent!==t;);if(!o)return null;const r=`/bl:${e}`;let i=null;for(;(i=n.nextNode())&&i.textContent!==r;);return i?{startMarker:o,endMarker:i}:null}(e);if(n){const{startMarker:e,endMarker:o}=n;if(pi)Kr({startExclusive:e,endExclusive:o},t);else{const n=o.parentNode,r=new Range;for(r.setStart(e,e.textContent.length),r.setEnd(o,0),r.deleteContents();t.childNodes[0];)n.insertBefore(t.childNodes[0],o)}ui.documentUpdated()}}(t,e.content);else switch(e.getAttribute("type")){case"redirection":const t=Ne(e.content.textContent),n="form-post"===e.getAttribute("from");"true"===e.getAttribute("enhanced")&&Re(t)?(n?history.pushState(null,"",t):history.replaceState(null,"",t),li(t)):n?location.assign(t):location.replace(t);break;case"error":hi(e.content.textContent||"Error")}}}))}}class gi{constructor(e){var t;this._circuitInactivityTimeoutMs=e,this._rootComponents=new Set,this._descriptors=new Set,this._pendingComponentsToResolve=new Map,this._didWebAssemblyFailToLoadQuickly=!1,this._isComponentRefreshPending=!1,this.initialComponents=[],t=()=>{this.rootComponentsMayRequireRefresh()},C.push(t)}onAfterRenderBatch(e){e===xn.Server&&this.circuitMayHaveNoRootComponents()}onDocumentUpdated(){this.rootComponentsMayRequireRefresh()}onEnhancedNavigationCompleted(){this.rootComponentsMayRequireRefresh()}registerComponent(e){this._descriptors.has(e)||("auto"!==e.type&&"webassembly"!==e.type||this.startLoadingWebAssemblyIfNotStarted(),this._descriptors.add(e),this._rootComponents.add({descriptor:e}))}unregisterComponent(e){this._descriptors.delete(e.descriptor),this._rootComponents.delete(e)}async startLoadingWebAssemblyIfNotStarted(){if(void 0!==kr)return;const e=Ar();setTimeout((()=>{Nr()||this.onWebAssemblyFailedToLoadQuickly()}),pt._internal.loadWebAssemblyQuicklyTimeout);const t=await xr;(function(e){if(!e.cacheBootResources)return!1;const t=mi(e);if(!t)return!1;const n=window.localStorage.getItem(t.key);return t.value===n})(t)||this.onWebAssemblyFailedToLoadQuickly(),await e,function(e){const t=mi(e);t&&window.localStorage.setItem(t.key,t.value)}(t),this.rootComponentsMayRequireRefresh()}onWebAssemblyFailedToLoadQuickly(){this._didWebAssemblyFailToLoadQuickly||(this._didWebAssemblyFailToLoadQuickly=!0,this.rootComponentsMayRequireRefresh())}startCircutIfNotStarted(){return Wo?Oo.isDisposedOrDisposing()?function(){if(!Wo)throw new Error("Cannot start the circuit until Blazor Server has started.");return Oo.didRenderingFail()?Promise.resolve(!1):(Oo.isDisposedOrDisposing()&&(Oo=new Ao(Oo.getRootComponentManager(),Fo,$o,Ho)),Oo.start())}():void 0:async function(e){if(Wo)throw new Error("Blazor Server has already started.");Wo=!0,Fo=wt(document)||"",Ho=new mt($o.logLevel),Oo=new Ao(e,Fo,$o,Ho),Ho.log(ft.Information,"Starting up Blazor server-side application."),pt.reconnect=async()=>!(Oo.didRenderingFail()||!await Oo.reconnect()&&(Ho.log(ft.Information,"Reconnection attempt to the circuit was rejected by the server. This may indicate that the associated state is no longer available on the server."),1)),pt.defaultReconnectionHandler=new Uo(Ho),$o.reconnectionHandler=$o.reconnectionHandler||pt.defaultReconnectionHandler,pt._internal.navigationManager.listenForNavigationEvents(((e,t,n)=>Oo.sendLocationChanged(e,t,n)),((e,t,n,o)=>Oo.sendLocationChanging(e,t,n,o))),pt._internal.forceCloseConnection=()=>Oo.disconnect(),pt._internal.sendJSDataStream=(e,t,n)=>Oo.sendJsDataStream(e,t,n);const t=await async function(e){const t=await fetch("_blazor/initializers",{method:"GET",credentials:"include",cache:"no-cache"}),n=await t.json(),o=new Bo;return await o.importInitializersAsync(n,[e]),o}($o);if(!await Oo.start())return void Ho.log(ft.Error,"Failed to start the circuit.");const n=()=>{Oo.sendDisconnectBeacon()};pt.disconnect=n,window.addEventListener("unload",n,{capture:!1,once:!0}),Ho.log(ft.Information,"Blazor server-side application started."),t.invokeAfterStartedCallbacks(pt)}(this)}async startWebAssemblyIfNotStarted(){this.startLoadingWebAssemblyIfNotStarted(),Rr||await async function(e){if(Rr)throw new Error("Blazor WebAssembly has already started.");Rr=!0,function(){if(window.parent!==window&&!window.opener&&window.frameElement){const e=window.sessionStorage&&window.sessionStorage["Microsoft.AspNetCore.Components.WebAssembly.Authentication.CachedAuthSettings"],t=e&&JSON.parse(e);return t&&t.redirect_uri&&location.href.startsWith(t.redirect_uri)}return!1}()&&await new Promise((()=>{}));const t=Ar();!function(e){const t=R;R=(e,n,o)=>{((e,t,n)=>{const o=Se(e);(null==o?void 0:o.eventDelegator.getHandler(t))&&lr.invokeWhenHeapUnlocked(n)})(e,n,(()=>t(e,n,o)))}}(),pt._internal.applyHotReload=(e,t,n,o)=>{nr.invokeDotNetStaticMethod("Microsoft.AspNetCore.Components.WebAssembly","ApplyHotReloadDelta",e,t,n,o)},pt._internal.getApplyUpdateCapabilities=()=>nr.invokeDotNetStaticMethod("Microsoft.AspNetCore.Components.WebAssembly","GetApplyUpdateCapabilities"),pt._internal.invokeJSFromDotNet=Mr,pt._internal.invokeJSJson=Pr,pt._internal.endInvokeDotNetFromJS=Ur,pt._internal.receiveWebAssemblyDotNetDataStream=Lr,pt._internal.receiveByteArray=Br;const n=zo(lr);pt.platform=n,pt._internal.renderBatch=(e,t)=>{const n=lr.beginHeapLock();try{Ce(e,new yr(t))}finally{n.release()}},pt._internal.navigationManager.listenForNavigationEvents((async(e,t,n)=>{await nr.invokeDotNetStaticMethodAsync("Microsoft.AspNetCore.Components.WebAssembly","NotifyLocationChanged",e,t,n)}),(async(e,t,n,o)=>{const r=await nr.invokeDotNetStaticMethodAsync("Microsoft.AspNetCore.Components.WebAssembly","NotifyLocationChangingAsync",t,n,o);pt._internal.navigationManager.endLocationChanging(e,r)}));const o=new Cr(e);let r;pt._internal.registeredComponents={getRegisteredComponentsCount:()=>o.getCount(),getAssembly:e=>o.getAssembly(e),getTypeName:e=>o.getTypeName(e),getParameterDefinitions:e=>o.getParameterDefinitions(e)||"",getParameterValues:e=>o.getParameterValues(e)||""},pt._internal.getPersistedState=()=>wt(document)||"",pt._internal.attachRootComponentToElement=(e,t,n)=>{const r=o.resolveRegisteredElement(e,t);r?Ee(n,r,t,!1):function(e,t,n){const o="::before";let r=!1;if(e.endsWith("::after"))e=e.slice(0,-7),r=!0;else if(e.endsWith(o))throw new Error(`The '${o}' selector is not supported.`);const i=w(e)||document.querySelector(e);if(!i)throw new Error(`Could not find any element matching selector '${e}'.`);Ee(n||0,H(i,!0),t,r)}(e,t,n)};try{await t,r=await n.start()}catch(e){throw new Error(`Failed to start platform. Reason: ${e}`)}n.callEntryPoint(),r.invokeLibraryInitializers("afterStarted",[pt])}(this)}rootComponentsMayRequireRefresh(){this._isComponentRefreshPending||(this._isComponentRefreshPending=!0,setTimeout((()=>{this._isComponentRefreshPending=!1,this.refreshRootComponents(this._rootComponents)}),0))}circuitMayHaveNoRootComponents(){if(this.hasAnyExistingOrPendingServerComponents())return clearTimeout(this._circuitInactivityTimeoutId),void(this._circuitInactivityTimeoutId=void 0);void 0===this._circuitInactivityTimeoutId&&(this._circuitInactivityTimeoutId=setTimeout((()=>{this.hasAnyExistingOrPendingServerComponents()||(async function(){await(null==Oo?void 0:Oo.dispose())}(),this._circuitInactivityTimeoutId=void 0)}),this._circuitInactivityTimeoutMs))}hasAnyExistingOrPendingServerComponents(){const e=Se(xn.Server);if(e&&e.getRootComponentCount()>0)return!0;for(const{descriptor:{type:e},assignedRendererId:t}of this._rootComponents){if(t===xn.Server)return!0;if(void 0===t&&("auto"===e||"server"===e))return!0}return!1}refreshRootComponents(e){const t=new Map;for(const n of e){const e=this.determinePendingOperation(n);if(!e)continue;const o=n.assignedRendererId;if(!o)throw new Error("Descriptors must be assigned a renderer ID before getting used as root components");let r=t.get(o);r||(r=[],t.set(o,r)),r.push(e)}for(const[e,r]of t)n=e,o=JSON.stringify(r),D(n).invokeMethodAsync("UpdateRootComponents",o);var n,o;this.circuitMayHaveNoRootComponents()}resolveRendererIdForDescriptor(e){switch("auto"===e.type?this.getAutoRenderMode():e.type){case"server":return this.startCircutIfNotStarted(),xn.Server;case"webassembly":return this.startWebAssemblyIfNotStarted(),xn.WebAssembly;case null:return null}}getAutoRenderMode(){return Nr()?"webassembly":this._didWebAssemblyFailToLoadQuickly?"server":null}determinePendingOperation(e){if(n=e.descriptor,document.contains(n.start)){if(void 0===e.assignedRendererId){if(zr||"loading"===document.readyState)return null;const n=this.resolveRendererIdForDescriptor(e.descriptor);return null===n?null:(t=n,S.has(t)?(e.assignedRendererId=n,e.uniqueIdAtLastUpdate=e.descriptor.uniqueId,this._pendingComponentsToResolve.set(e.descriptor.uniqueId,e),{type:"add",selectorId:e.descriptor.uniqueId,marker:Dt(e.descriptor)}):null)}if(e.uniqueIdAtLastUpdate===e.descriptor.uniqueId)return null;if(void 0!==e.interactiveComponentId)return e.uniqueIdAtLastUpdate=e.descriptor.uniqueId,{type:"update",componentId:e.interactiveComponentId,marker:Dt(e.descriptor)}}else if(this.unregisterComponent(e),void 0!==e.interactiveComponentId)return{type:"remove",componentId:e.interactiveComponentId};var t,n;return null}resolveRootComponent(e,t){const n=this._pendingComponentsToResolve.get(e);if(!n)throw new Error(`Could not resolve a root component for descriptor with ID '${e}'.`);if(this._pendingComponentsToResolve.delete(e),void 0!==n.interactiveComponentId)throw new Error("Cannot resolve a root component for the same descriptor multiple times.");return n.interactiveComponentId=t,this.refreshRootComponents([n]),n.descriptor}}function mi(e){var t;const n=null===(t=e.resources)||void 0===t?void 0:t.hash,o=e.mainAssemblyName;return n&&o?{key:`blazor-resource-hash:${o}`,value:n}:null}class yi{constructor(){this._eventListeners=new Map}static create(e){const t=new yi;return e.addEventListener=t.addEventListener.bind(t),e.removeEventListener=t.removeEventListener.bind(t),t}addEventListener(e,t){let n=this._eventListeners.get(e);n||(n=new Set,this._eventListeners.set(e,n)),n.add(t)}removeEventListener(e,t){var n;null===(n=this._eventListeners.get(e))||void 0===n||n.delete(t)}dispatchEvent(e,t){const n=this._eventListeners.get(e);if(!n)return;const o={...t,type:e};for(const e of n)e(o)}}let vi,wi=!1;function bi(e){var t,n,o;if(wi)throw new Error("Blazor has already started.");wi=!0,pt._internal.loadWebAssemblyQuicklyTimeout=3e3,pt._internal.hotReloadApplied=()=>{xe()&&Ae(location.href,!0)},qo(null==e?void 0:e.circuit),function(e){if(Ir)throw new Error("WebAssembly options have already been configured.");Ir=e}(null==e?void 0:e.webAssembly),vi=new gi(null!==(n=null===(t=null==e?void 0:e.ssr)||void 0===t?void 0:t.circuitInactivityTimeoutMs)&&void 0!==n?n:2e3);const r=yi.create(pt),i={documentUpdated:()=>{vi.onDocumentUpdated(),r.dispatchEvent("enhancedload",{})},enhancedNavigationCompleted(){vi.onEnhancedNavigationCompleted()}};return Jr=vi,function(e,t){ui=t,(null==e?void 0:e.disableDomPreservation)&&(pi=!1),customElements.define("blazor-ssr-end",fi)}(null==e?void 0:e.ssr,i),(null===(o=null==e?void 0:e.ssr)||void 0===o?void 0:o.disableDomPreservation)||ri(i),"loading"===document.readyState?document.addEventListener("DOMContentLoaded",_i):_i(),Promise.resolve()}function _i(){!function(e){const t=Zr(document);for(const e of t)null==Jr||Jr.registerComponent(e)}(),vi.onDocumentUpdated()}pt.start=bi,window.DotNet=e,document&&document.currentScript&&"false"!==document.currentScript.getAttribute("autostart")&&bi()})()})(); \ No newline at end of file +(()=>{var e={778:()=>{},77:()=>{},203:()=>{},200:()=>{},628:()=>{},321:()=>{}},t={};function n(o){var r=t[o];if(void 0!==r)return r.exports;var i=t[o]={exports:{}};return e[o](i,i.exports,n),i.exports}n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),(()=>{"use strict";var e,t,o;!function(e){const t=[],n="__jsObjectId",o="__dotNetObject",r="__byte[]",i="__dotNetStream",s="__jsStreamReferenceLength";let a,c;class l{constructor(e){this._jsObject=e,this._cachedFunctions=new Map}findFunction(e){const t=this._cachedFunctions.get(e);if(t)return t;let n,o=this._jsObject;if(e.split(".").forEach((t=>{if(!(t in o))throw new Error(`Could not find '${e}' ('${t}' was undefined).`);n=o,o=o[t]})),o instanceof Function)return o=o.bind(n),this._cachedFunctions.set(e,o),o;throw new Error(`The value '${e}' is not a function.`)}getWrappedObject(){return this._jsObject}}const h={0:new l(window)};h[0]._cachedFunctions.set("import",(e=>("string"==typeof e&&e.startsWith("./")&&(e=new URL(e.substr(2),document.baseURI).toString()),import(e))));let d,u=1;function p(e){t.push(e)}function f(e){if(e&&"object"==typeof e){h[u]=new l(e);const t={[n]:u};return u++,t}throw new Error(`Cannot create a JSObjectReference from the value '${e}'.`)}function g(e){let t=-1;if(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),e instanceof Blob)t=e.size;else{if(!(e.buffer instanceof ArrayBuffer))throw new Error("Supplied value is not a typed array or blob.");if(void 0===e.byteLength)throw new Error(`Cannot create a JSStreamReference from the value '${e}' as it doesn't have a byteLength.`);t=e.byteLength}const o={[s]:t};try{const t=f(e);o[n]=t[n]}catch(t){throw new Error(`Cannot create a JSStreamReference from the value '${e}'.`)}return o}function m(e,n){c=e;const o=n?JSON.parse(n,((e,n)=>t.reduce(((t,n)=>n(e,t)),n))):null;return c=void 0,o}function v(){if(void 0===a)throw new Error("No call dispatcher has been set.");if(null===a)throw new Error("There are multiple .NET runtimes present, so a default dispatcher could not be resolved. Use DotNetObject to invoke .NET instance methods.");return a}e.attachDispatcher=function(e){const t=new y(e);return void 0===a?a=t:a&&(a=null),t},e.attachReviver=p,e.invokeMethod=function(e,t,...n){return v().invokeDotNetStaticMethod(e,t,...n)},e.invokeMethodAsync=function(e,t,...n){return v().invokeDotNetStaticMethodAsync(e,t,...n)},e.createJSObjectReference=f,e.createJSStreamReference=g,e.disposeJSObjectReference=function(e){const t=e&&e[n];"number"==typeof t&&_(t)},function(e){e[e.Default=0]="Default",e[e.JSObjectReference=1]="JSObjectReference",e[e.JSStreamReference=2]="JSStreamReference",e[e.JSVoidResult=3]="JSVoidResult"}(d=e.JSCallResultType||(e.JSCallResultType={}));class y{constructor(e){this._dotNetCallDispatcher=e,this._byteArraysToBeRevived=new Map,this._pendingDotNetToJSStreams=new Map,this._pendingAsyncCalls={},this._nextAsyncCallId=1}getDotNetCallDispatcher(){return this._dotNetCallDispatcher}invokeJSFromDotNet(e,t,n,o){const r=m(this,t),i=I(b(e,o)(...r||[]),n);return null==i?null:T(this,i)}beginInvokeJSFromDotNet(e,t,n,o,r){const i=new Promise((e=>{const o=m(this,n);e(b(t,r)(...o||[]))}));e&&i.then((t=>T(this,[e,!0,I(t,o)]))).then((t=>this._dotNetCallDispatcher.endInvokeJSFromDotNet(e,!0,t)),(t=>this._dotNetCallDispatcher.endInvokeJSFromDotNet(e,!1,JSON.stringify([e,!1,w(t)]))))}endInvokeDotNetFromJS(e,t,n){const o=t?m(this,n):new Error(n);this.completePendingCall(parseInt(e,10),t,o)}invokeDotNetStaticMethod(e,t,...n){return this.invokeDotNetMethod(e,t,null,n)}invokeDotNetStaticMethodAsync(e,t,...n){return this.invokeDotNetMethodAsync(e,t,null,n)}invokeDotNetMethod(e,t,n,o){if(this._dotNetCallDispatcher.invokeDotNetFromJS){const r=T(this,o),i=this._dotNetCallDispatcher.invokeDotNetFromJS(e,t,n,r);return i?m(this,i):null}throw new Error("The current dispatcher does not support synchronous calls from JS to .NET. Use invokeDotNetMethodAsync instead.")}invokeDotNetMethodAsync(e,t,n,o){if(e&&n)throw new Error(`For instance method calls, assemblyName should be null. Received '${e}'.`);const r=this._nextAsyncCallId++,i=new Promise(((e,t)=>{this._pendingAsyncCalls[r]={resolve:e,reject:t}}));try{const i=T(this,o);this._dotNetCallDispatcher.beginInvokeDotNetFromJS(r,e,t,n,i)}catch(e){this.completePendingCall(r,!1,e)}return i}receiveByteArray(e,t){this._byteArraysToBeRevived.set(e,t)}processByteArray(e){const t=this._byteArraysToBeRevived.get(e);return t?(this._byteArraysToBeRevived.delete(e),t):null}supplyDotNetStream(e,t){if(this._pendingDotNetToJSStreams.has(e)){const n=this._pendingDotNetToJSStreams.get(e);this._pendingDotNetToJSStreams.delete(e),n.resolve(t)}else{const n=new C;n.resolve(t),this._pendingDotNetToJSStreams.set(e,n)}}getDotNetStreamPromise(e){let t;if(this._pendingDotNetToJSStreams.has(e))t=this._pendingDotNetToJSStreams.get(e).streamPromise,this._pendingDotNetToJSStreams.delete(e);else{const n=new C;this._pendingDotNetToJSStreams.set(e,n),t=n.streamPromise}return t}completePendingCall(e,t,n){if(!this._pendingAsyncCalls.hasOwnProperty(e))throw new Error(`There is no pending async call with ID ${e}.`);const o=this._pendingAsyncCalls[e];delete this._pendingAsyncCalls[e],t?o.resolve(n):o.reject(n)}}function w(e){return e instanceof Error?`${e.message}\n${e.stack}`:e?e.toString():"null"}function b(e,t){const n=h[t];if(n)return n.findFunction(e);throw new Error(`JS object instance with ID ${t} does not exist (has it been disposed?).`)}function _(e){delete h[e]}e.findJSFunction=b,e.disposeJSObjectReferenceById=_;class E{constructor(e,t){this._id=e,this._callDispatcher=t}invokeMethod(e,...t){return this._callDispatcher.invokeDotNetMethod(null,e,this._id,t)}invokeMethodAsync(e,...t){return this._callDispatcher.invokeDotNetMethodAsync(null,e,this._id,t)}dispose(){this._callDispatcher.invokeDotNetMethodAsync(null,"__Dispose",this._id,null).catch((e=>console.error(e)))}serializeAsArg(){return{[o]:this._id}}}e.DotNetObject=E,p((function(e,t){if(t&&"object"==typeof t){if(t.hasOwnProperty(o))return new E(t[o],c);if(t.hasOwnProperty(n)){const e=t[n],o=h[e];if(o)return o.getWrappedObject();throw new Error(`JS object instance with Id '${e}' does not exist. It may have been disposed.`)}if(t.hasOwnProperty(r)){const e=t[r],n=c.processByteArray(e);if(void 0===n)throw new Error(`Byte array index '${e}' does not exist.`);return n}if(t.hasOwnProperty(i)){const e=t[i],n=c.getDotNetStreamPromise(e);return new S(n)}}return t}));class S{constructor(e){this._streamPromise=e}stream(){return this._streamPromise}async arrayBuffer(){return new Response(await this.stream()).arrayBuffer()}}class C{constructor(){this.streamPromise=new Promise(((e,t)=>{this.resolve=e,this.reject=t}))}}function I(e,t){switch(t){case d.Default:return e;case d.JSObjectReference:return f(e);case d.JSStreamReference:return g(e);case d.JSVoidResult:return null;default:throw new Error(`Invalid JS call result type '${t}'.`)}}let k=0;function T(e,t){k=0,c=e;const n=JSON.stringify(t,D);return c=void 0,n}function D(e,t){if(t instanceof E)return t.serializeAsArg();if(t instanceof Uint8Array){c.getDotNetCallDispatcher().sendByteArray(k,t);const e={[r]:k};return k++,e}return t}}(e||(e={})),function(e){e[e.prependFrame=1]="prependFrame",e[e.removeFrame=2]="removeFrame",e[e.setAttribute=3]="setAttribute",e[e.removeAttribute=4]="removeAttribute",e[e.updateText=5]="updateText",e[e.stepIn=6]="stepIn",e[e.stepOut=7]="stepOut",e[e.updateMarkup=8]="updateMarkup",e[e.permutationListEntry=9]="permutationListEntry",e[e.permutationListEnd=10]="permutationListEnd"}(t||(t={})),function(e){e[e.element=1]="element",e[e.text=2]="text",e[e.attribute=3]="attribute",e[e.component=4]="component",e[e.region=5]="region",e[e.elementReferenceCapture=6]="elementReferenceCapture",e[e.markup=8]="markup",e[e.namedEvent=10]="namedEvent"}(o||(o={}));class r{constructor(e,t){this.componentId=e,this.fieldValue=t}static fromEvent(e,t){const n=t.target;if(n instanceof Element){const t=function(e){return e instanceof HTMLInputElement?e.type&&"checkbox"===e.type.toLowerCase()?{value:e.checked}:{value:e.value}:e instanceof HTMLSelectElement||e instanceof HTMLTextAreaElement?{value:e.value}:null}(n);if(t)return new r(e,t.value)}return null}}const i=new Map,s=new Map,a=[];function c(e){return i.get(e)}function l(e){const t=i.get(e);return(null==t?void 0:t.browserEventName)||e}function h(e,t){e.forEach((e=>i.set(e,t)))}function d(e){const t=[];for(let n=0;ne.selected)).map((e=>e.value))}}{const e=function(e){return!!e&&"INPUT"===e.tagName&&"checkbox"===e.getAttribute("type")}(t);return{value:e?!!t.checked:t.value}}}}),h(["copy","cut","paste"],{createEventArgs:e=>({type:e.type})}),h(["drag","dragend","dragenter","dragleave","dragover","dragstart","drop"],{createEventArgs:e=>{return{...u(t=e),dataTransfer:t.dataTransfer?{dropEffect:t.dataTransfer.dropEffect,effectAllowed:t.dataTransfer.effectAllowed,files:Array.from(t.dataTransfer.files).map((e=>e.name)),items:Array.from(t.dataTransfer.items).map((e=>({kind:e.kind,type:e.type}))),types:t.dataTransfer.types}:null};var t}}),h(["focus","blur","focusin","focusout"],{createEventArgs:e=>({type:e.type})}),h(["keydown","keyup","keypress"],{createEventArgs:e=>{return{key:(t=e).key,code:t.code,location:t.location,repeat:t.repeat,ctrlKey:t.ctrlKey,shiftKey:t.shiftKey,altKey:t.altKey,metaKey:t.metaKey,type:t.type};var t}}),h(["contextmenu","click","mouseover","mouseout","mousemove","mousedown","mouseup","mouseleave","mouseenter","dblclick"],{createEventArgs:e=>u(e)}),h(["error"],{createEventArgs:e=>{return{message:(t=e).message,filename:t.filename,lineno:t.lineno,colno:t.colno,type:t.type};var t}}),h(["loadstart","timeout","abort","load","loadend","progress"],{createEventArgs:e=>{return{lengthComputable:(t=e).lengthComputable,loaded:t.loaded,total:t.total,type:t.type};var t}}),h(["touchcancel","touchend","touchmove","touchenter","touchleave","touchstart"],{createEventArgs:e=>{return{detail:(t=e).detail,touches:d(t.touches),targetTouches:d(t.targetTouches),changedTouches:d(t.changedTouches),ctrlKey:t.ctrlKey,shiftKey:t.shiftKey,altKey:t.altKey,metaKey:t.metaKey,type:t.type};var t}}),h(["gotpointercapture","lostpointercapture","pointercancel","pointerdown","pointerenter","pointerleave","pointermove","pointerout","pointerover","pointerup"],{createEventArgs:e=>{return{...u(t=e),pointerId:t.pointerId,width:t.width,height:t.height,pressure:t.pressure,tiltX:t.tiltX,tiltY:t.tiltY,pointerType:t.pointerType,isPrimary:t.isPrimary};var t}}),h(["wheel","mousewheel"],{createEventArgs:e=>{return{...u(t=e),deltaX:t.deltaX,deltaY:t.deltaY,deltaZ:t.deltaZ,deltaMode:t.deltaMode};var t}}),h(["cancel","close","toggle"],{createEventArgs:()=>({})});const p=["date","datetime-local","month","time","week"],f=new Map;let g,m,v=0;const y={async add(e,t,n){if(!n)throw new Error("initialParameters must be an object, even if empty.");const o="__bl-dynamic-root:"+(++v).toString();f.set(o,e);const r=await E().invokeMethodAsync("AddRootComponent",t,o),i=new _(r,m[t]);return await i.setParameters(n),i}};function w(e){const t=f.get(e);if(t)return f.delete(e),t}class b{invoke(e){return this._callback(e)}setCallback(t){this._selfJSObjectReference||(this._selfJSObjectReference=e.createJSObjectReference(this)),this._callback=t}getJSObjectReference(){return this._selfJSObjectReference}dispose(){this._selfJSObjectReference&&e.disposeJSObjectReference(this._selfJSObjectReference)}}class _{constructor(e,t){this._jsEventCallbackWrappers=new Map,this._componentId=e;for(const e of t)"eventcallback"===e.type&&this._jsEventCallbackWrappers.set(e.name.toLowerCase(),new b)}setParameters(e){const t={},n=Object.entries(e||{}),o=n.length;for(const[e,o]of n){const n=this._jsEventCallbackWrappers.get(e.toLowerCase());n&&o?(n.setCallback(o),t[e]=n.getJSObjectReference()):t[e]=o}return E().invokeMethodAsync("SetRootComponentParameters",this._componentId,o,t)}async dispose(){if(null!==this._componentId){await E().invokeMethodAsync("RemoveRootComponent",this._componentId),this._componentId=null;for(const e of this._jsEventCallbackWrappers.values())e.dispose()}}}function E(){if(!g)throw new Error("Dynamic root components have not been enabled in this application.");return g}const S=new Map,C=[];let I;const k=new Promise((e=>{I=e}));function T(e,t,n){return R(e,t.eventHandlerId,(()=>D(e).invokeMethodAsync("DispatchEventAsync",t,n)))}function D(e){const t=S.get(e);if(!t)throw new Error(`No interop methods are registered for renderer ${e}`);return t}let R=(e,t,n)=>n();const A=L(["abort","blur","cancel","canplay","canplaythrough","change","close","cuechange","durationchange","emptied","ended","error","focus","load","loadeddata","loadedmetadata","loadend","loadstart","mouseenter","mouseleave","pointerenter","pointerleave","pause","play","playing","progress","ratechange","reset","scroll","seeked","seeking","stalled","submit","suspend","timeupdate","toggle","unload","volumechange","waiting","DOMNodeInsertedIntoDocument","DOMNodeRemovedFromDocument"]),x={submit:!0},N=L(["click","dblclick","mousedown","mousemove","mouseup"]);class M{constructor(e){this.browserRendererId=e,this.afterClickCallbacks=[];const t=++M.nextEventDelegatorId;this.eventsCollectionKey=`_blazorEvents_${t}`,this.eventInfoStore=new P(this.onGlobalEvent.bind(this))}setListener(e,t,n,o){const r=this.getEventHandlerInfosForElement(e,!0),i=r.getHandler(t);if(i)this.eventInfoStore.update(i.eventHandlerId,n);else{const i={element:e,eventName:t,eventHandlerId:n,renderingComponentId:o};this.eventInfoStore.add(i),r.setHandler(t,i)}}getHandler(e){return this.eventInfoStore.get(e)}removeListener(e){const t=this.eventInfoStore.remove(e);if(t){const e=t.element,n=this.getEventHandlerInfosForElement(e,!1);n&&n.removeHandler(t.eventName)}}notifyAfterClick(e){this.afterClickCallbacks.push(e),this.eventInfoStore.addGlobalListener("click")}setStopPropagation(e,t,n){this.getEventHandlerInfosForElement(e,!0).stopPropagation(t,n)}setPreventDefault(e,t,n){this.getEventHandlerInfosForElement(e,!0).preventDefault(t,n)}onGlobalEvent(e){if(!(e.target instanceof Element))return;this.dispatchGlobalEventToAllElements(e.type,e);const t=(n=e.type,s.get(n));var n;t&&t.forEach((t=>this.dispatchGlobalEventToAllElements(t,e))),"click"===e.type&&this.afterClickCallbacks.forEach((t=>t(e)))}dispatchGlobalEventToAllElements(e,t){const n=t.composedPath();let o=n.shift(),i=null,s=!1;const a=Object.prototype.hasOwnProperty.call(A,e);let l=!1;for(;o;){const u=o,p=this.getEventHandlerInfosForElement(u,!1);if(p){const n=p.getHandler(e);if(n&&(h=u,d=t.type,!((h instanceof HTMLButtonElement||h instanceof HTMLInputElement||h instanceof HTMLTextAreaElement||h instanceof HTMLSelectElement)&&Object.prototype.hasOwnProperty.call(N,d)&&h.disabled))){if(!s){const n=c(e);i=(null==n?void 0:n.createEventArgs)?n.createEventArgs(t):{},s=!0}Object.prototype.hasOwnProperty.call(x,t.type)&&t.preventDefault(),T(this.browserRendererId,{eventHandlerId:n.eventHandlerId,eventName:e,eventFieldInfo:r.fromEvent(n.renderingComponentId,t)},i)}p.stopPropagation(e)&&(l=!0),p.preventDefault(e)&&t.preventDefault()}o=a||l?void 0:n.shift()}var h,d}getEventHandlerInfosForElement(e,t){return Object.prototype.hasOwnProperty.call(e,this.eventsCollectionKey)?e[this.eventsCollectionKey]:t?e[this.eventsCollectionKey]=new U:null}}M.nextEventDelegatorId=0;class P{constructor(e){this.globalListener=e,this.infosByEventHandlerId={},this.countByEventName={},a.push(this.handleEventNameAliasAdded.bind(this))}add(e){if(this.infosByEventHandlerId[e.eventHandlerId])throw new Error(`Event ${e.eventHandlerId} is already tracked`);this.infosByEventHandlerId[e.eventHandlerId]=e,this.addGlobalListener(e.eventName)}get(e){return this.infosByEventHandlerId[e]}addGlobalListener(e){if(e=l(e),Object.prototype.hasOwnProperty.call(this.countByEventName,e))this.countByEventName[e]++;else{this.countByEventName[e]=1;const t=Object.prototype.hasOwnProperty.call(A,e);document.addEventListener(e,this.globalListener,t)}}update(e,t){if(Object.prototype.hasOwnProperty.call(this.infosByEventHandlerId,t))throw new Error(`Event ${t} is already tracked`);const n=this.infosByEventHandlerId[e];delete this.infosByEventHandlerId[e],n.eventHandlerId=t,this.infosByEventHandlerId[t]=n}remove(e){const t=this.infosByEventHandlerId[e];if(t){delete this.infosByEventHandlerId[e];const n=l(t.eventName);0==--this.countByEventName[n]&&(delete this.countByEventName[n],document.removeEventListener(n,this.globalListener))}return t}handleEventNameAliasAdded(e,t){if(Object.prototype.hasOwnProperty.call(this.countByEventName,e)){const n=this.countByEventName[e];delete this.countByEventName[e],document.removeEventListener(e,this.globalListener),this.addGlobalListener(t),this.countByEventName[t]+=n-1}}}class U{constructor(){this.handlers={},this.preventDefaultFlags=null,this.stopPropagationFlags=null}getHandler(e){return Object.prototype.hasOwnProperty.call(this.handlers,e)?this.handlers[e]:null}setHandler(e,t){this.handlers[e]=t}removeHandler(e){delete this.handlers[e]}preventDefault(e,t){return void 0!==t&&(this.preventDefaultFlags=this.preventDefaultFlags||{},this.preventDefaultFlags[e]=t),!!this.preventDefaultFlags&&this.preventDefaultFlags[e]}stopPropagation(e,t){return void 0!==t&&(this.stopPropagationFlags=this.stopPropagationFlags||{},this.stopPropagationFlags[e]=t),!!this.stopPropagationFlags&&this.stopPropagationFlags[e]}}function L(e){const t={};return e.forEach((e=>{t[e]=!0})),t}const B=Symbol(),F=Symbol(),O=Symbol();function $(e){const{start:t,end:n}=e,o=t[O];if(o){if(o!==e)throw new Error("The start component comment was already associated with another component descriptor.");return t}const r=t.parentNode;if(!r)throw new Error(`Comment not connected to the DOM ${t.textContent}`);const i=H(r,!0),s=G(i);t[F]=i,t[O]=e;const a=H(t);if(n){const e=G(a),o=Array.prototype.indexOf.call(s,a)+1;let r=null;for(;r!==n;){const n=s.splice(o,1)[0];if(!n)throw new Error("Could not find the end component comment in the parent logical node list");n[F]=t,e.push(n),r=n}}return a}function H(e,t){if(B in e)return e;const n=[];if(e.childNodes.length>0){if(!t)throw new Error("New logical elements must start empty, or allowExistingContents must be true");e.childNodes.forEach((t=>{const o=H(t,!0);o[F]=e,n.push(o)}))}return e[B]=n,e}function j(e){const t=G(e);for(;t.length;)z(e,0)}function W(e,t){const n=document.createComment("!");return q(n,e,t),n}function q(e,t,n){const o=e;let r=e;if(Q(e)){const t=ne(o);if(t!==e){const n=new Range;n.setStartBefore(e),n.setEndAfter(t),r=n.extractContents()}}const i=J(o);if(i){const e=G(i),t=Array.prototype.indexOf.call(e,o);e.splice(t,1),delete o[F]}const s=G(t);if(n0;)z(n,0)}const o=n;o.parentNode.removeChild(o)}function J(e){return e[F]||null}function V(e,t){return G(e)[t]}function K(e){return e[O]||null}function X(e){const t=ee(e);return"http://www.w3.org/2000/svg"===t.namespaceURI&&"foreignObject"!==t.tagName}function G(e){return e[B]}function Y(e){const t=G(J(e));return t[Array.prototype.indexOf.call(t,e)+1]||null}function Q(e){return B in e}function Z(e,t){const n=G(e);t.forEach((e=>{e.moveRangeStart=n[e.fromSiblingIndex],e.moveRangeEnd=ne(e.moveRangeStart)})),t.forEach((t=>{const o=document.createComment("marker");t.moveToBeforeMarker=o;const r=n[t.toSiblingIndex+1];r?r.parentNode.insertBefore(o,r):te(o,e)})),t.forEach((e=>{const t=e.moveToBeforeMarker,n=t.parentNode,o=e.moveRangeStart,r=e.moveRangeEnd;let i=o;for(;i;){const e=i.nextSibling;if(n.insertBefore(i,t),i===r)break;i=e}n.removeChild(t)})),t.forEach((e=>{n[e.toSiblingIndex]=e.moveRangeStart}))}function ee(e){if(e instanceof Element||e instanceof DocumentFragment)return e;if(e instanceof Comment)return e.parentNode;throw new Error("Not a valid logical element")}function te(e,t){if(t instanceof Element||t instanceof DocumentFragment)t.appendChild(e);else{if(!(t instanceof Comment))throw new Error(`Cannot append node because the parent is not a valid logical element. Parent: ${t}`);{const n=Y(t);n?n.parentNode.insertBefore(e,n):te(e,J(t))}}}function ne(e){if(e instanceof Element||e instanceof DocumentFragment)return e;const t=Y(e);if(t)return t.previousSibling;{const t=J(e);return t instanceof Element||t instanceof DocumentFragment?t.lastChild:ne(t)}}function oe(e){return`_bl_${e}`}const re="__internalId";e.attachReviver(((e,t)=>t&&"object"==typeof t&&Object.prototype.hasOwnProperty.call(t,re)&&"string"==typeof t[re]?function(e){const t=`[${oe(e)}]`;return document.querySelector(t)}(t[re]):t));const ie="_blazorDeferredValue";function se(e){e instanceof HTMLOptionElement?he(e):ie in e&&le(e,e[ie])}function ae(e){return"select-multiple"===e.type}function ce(e,t){e.value=t||""}function le(e,t){e instanceof HTMLSelectElement?ae(e)?function(e,t){t||(t=[]);for(let n=0;n{Pe()&&De(e,(e=>{Je(e,!0,!1)}))}))}getRootComponentCount(){return this.rootComponentIds.size}attachRootComponentToLogicalElement(e,t,n){if(ve(t))throw new Error(`Root component '${e}' could not be attached because its target element is already associated with a root component`);me(t,!0),this.attachComponentToElement(e,t),this.rootComponentIds.add(e),n||(pe[e]=t)}updateComponent(e,t,n,o){var r;const i=this.childComponentLocations[t];if(!i)throw new Error(`No element is currently associated with component ${t}`);const s=pe[t];s&&(delete pe[t],j(s),s instanceof Comment&&(s.textContent="!"));const a=null===(r=ee(i))||void 0===r?void 0:r.getRootNode(),c=a&&a.activeElement;this.applyEdits(e,t,i,0,n,o),c instanceof HTMLElement&&a&&a.activeElement!==c&&c.focus()}disposeComponent(e){if(this.rootComponentIds.delete(e)){const t=this.childComponentLocations[e];me(t,!1),j(t)}delete this.childComponentLocations[e]}disposeEventHandler(e){this.eventDelegator.removeListener(e)}attachComponentToElement(e,t){this.childComponentLocations[e]=t}applyEdits(e,n,o,r,i,s){let a,c=0,l=r;const h=e.arrayBuilderSegmentReader,d=e.editReader,u=e.frameReader,p=h.values(i),f=h.offset(i),g=f+h.count(i);for(let i=f;idocument.baseURI,getLocationHref:()=>location.href,scrollToElement:qe};function qe(e){const t=document.getElementById(e);return!!t&&(t.scrollIntoView(),!0)}function ze(e,t,n=!1){const o=Ne(e);!t.forceLoad&&Re(o)?Ze()?Je(o,!1,t.replaceHistoryEntry,t.historyEntryState,n):xe(o,t.replaceHistoryEntry):function(e,t){if(location.href===e){const t=e+"?";history.replaceState(null,"",t),location.replace(e)}else t?location.replace(e):location.href=e}(e,t.replaceHistoryEntry)}async function Je(e,t,n,o=void 0,r=!1){if(Xe(),function(e){const t=e.indexOf("#");return t>-1&&location.href.replace(location.hash,"")===e.substring(0,t)}(e))!function(e,t,n){Ve(e,t,n);const o=e.indexOf("#");o!==e.length-1&&qe(e.substring(o+1))}(e,n,o);else{if(!r&&Le&&!await Ge(e,o,t))return;_e=!0,Ve(e,n,o),await Ye(t)}}function Ve(e,t,n=void 0){t?history.replaceState({userState:n,_index:Be},"",e):(Be++,history.pushState({userState:n,_index:Be},"",e))}function Ke(e){return new Promise((t=>{const n=He;He=()=>{He=n,t()},history.go(e)}))}function Xe(){je&&(je(!1),je=null)}function Ge(e,t,n){return new Promise((o=>{Xe(),$e?(Fe++,je=o,$e(Fe,e,t,n)):o(!1)}))}async function Ye(e){var t;Oe&&await Oe(location.href,null===(t=history.state)||void 0===t?void 0:t.userState,e)}async function Qe(e){var t,n;He&&Ze()&&await He(e),Be=null!==(n=null===(t=history.state)||void 0===t?void 0:t._index)&&void 0!==n?n:0}function Ze(){return Pe()||!Ae()}const et={focus:function(e,t){if(e instanceof HTMLElement)e.focus({preventScroll:t});else{if(!(e instanceof SVGElement))throw new Error("Unable to focus an invalid element.");if(!e.hasAttribute("tabindex"))throw new Error("Unable to focus an SVG element that does not have a tabindex.");e.focus({preventScroll:t})}},focusBySelector:function(e,t){const n=document.querySelector(e);n&&(n.hasAttribute("tabindex")||(n.tabIndex=-1),n.focus({preventScroll:!0}))}},tt={init:function(e,t,n,o=50){const r=ot(t);(r||document.documentElement).style.overflowAnchor="none";const i=document.createRange();u(n.parentElement)&&(t.style.display="table-row",n.style.display="table-row");const s=new IntersectionObserver((function(o){o.forEach((o=>{var r;if(!o.isIntersecting)return;i.setStartAfter(t),i.setEndBefore(n);const s=i.getBoundingClientRect().height,a=null===(r=o.rootBounds)||void 0===r?void 0:r.height;o.target===t?e.invokeMethodAsync("OnSpacerBeforeVisible",o.intersectionRect.top-o.boundingClientRect.top,s,a):o.target===n&&n.offsetHeight>0&&e.invokeMethodAsync("OnSpacerAfterVisible",o.boundingClientRect.bottom-o.intersectionRect.bottom,s,a)}))}),{root:r,rootMargin:`${o}px`});s.observe(t),s.observe(n);const a=d(t),c=d(n),{observersByDotNetObjectId:l,id:h}=rt(e);function d(e){const t={attributes:!0},n=new MutationObserver(((n,o)=>{u(e.parentElement)&&(o.disconnect(),e.style.display="table-row",o.observe(e,t)),s.unobserve(e),s.observe(e)}));return n.observe(e,t),n}function u(e){return null!==e&&(e instanceof HTMLTableElement&&""===e.style.display||"table"===e.style.display||e instanceof HTMLTableSectionElement&&""===e.style.display||"table-row-group"===e.style.display)}l[h]={intersectionObserver:s,mutationObserverBefore:a,mutationObserverAfter:c}},dispose:function(e){const{observersByDotNetObjectId:t,id:n}=rt(e),o=t[n];o&&(o.intersectionObserver.disconnect(),o.mutationObserverBefore.disconnect(),o.mutationObserverAfter.disconnect(),e.dispose(),delete t[n])}},nt=Symbol();function ot(e){return e&&e!==document.body&&e!==document.documentElement?"visible"!==getComputedStyle(e).overflowY?e:ot(e.parentElement):null}function rt(e){var t;const n=e._callDispatcher,o=e._id;return null!==(t=n[nt])&&void 0!==t||(n[nt]={}),{observersByDotNetObjectId:n[nt],id:o}}const it={getAndRemoveExistingTitle:function(){var e;const t=document.head?document.head.getElementsByTagName("title"):[];if(0===t.length)return null;let n=null;for(let o=t.length-1;o>=0;o--){const r=t[o],i=r.previousSibling;i instanceof Comment&&null!==J(i)||(null===n&&(n=r.textContent),null===(e=r.parentNode)||void 0===e||e.removeChild(r))}return n}},st={init:function(e,t){t._blazorInputFileNextFileId=0,t.addEventListener("click",(function(){t.value=""})),t.addEventListener("change",(function(){t._blazorFilesById={};const n=Array.prototype.map.call(t.files,(function(e){const n={id:++t._blazorInputFileNextFileId,lastModified:new Date(e.lastModified).toISOString(),name:e.name,size:e.size,contentType:e.type,readPromise:void 0,arrayBuffer:void 0,blob:e};return t._blazorFilesById[n.id]=n,n}));e.invokeMethodAsync("NotifyChange",n)}))},toImageFile:async function(e,t,n,o,r){const i=at(e,t),s=await new Promise((function(e){const t=new Image;t.onload=function(){URL.revokeObjectURL(t.src),e(t)},t.onerror=function(){t.onerror=null,URL.revokeObjectURL(t.src)},t.src=URL.createObjectURL(i.blob)})),a=await new Promise((function(e){var t;const i=Math.min(1,o/s.width),a=Math.min(1,r/s.height),c=Math.min(i,a),l=document.createElement("canvas");l.width=Math.round(s.width*c),l.height=Math.round(s.height*c),null===(t=l.getContext("2d"))||void 0===t||t.drawImage(s,0,0,l.width,l.height),l.toBlob(e,n)})),c={id:++e._blazorInputFileNextFileId,lastModified:i.lastModified,name:i.name,size:(null==a?void 0:a.size)||0,contentType:n,blob:a||i.blob};return e._blazorFilesById[c.id]=c,c},readFileData:async function(e,t){return at(e,t).blob}};function at(e,t){const n=e._blazorFilesById[t];if(!n)throw new Error(`There is no file with ID ${t}. The file list may have changed. See https://aka.ms/aspnet/blazor-input-file-multiple-selections.`);return n}const ct=new Set,lt={enableNavigationPrompt:function(e){0===ct.size&&window.addEventListener("beforeunload",ht),ct.add(e)},disableNavigationPrompt:function(e){ct.delete(e),0===ct.size&&window.removeEventListener("beforeunload",ht)}};function ht(e){e.preventDefault(),e.returnValue=!0}async function dt(e,t,n){return e instanceof Blob?await async function(e,t,n){const o=e.slice(t,t+n),r=await o.arrayBuffer();return new Uint8Array(r)}(e,t,n):function(e,t,n){return new Uint8Array(e.buffer,e.byteOffset+t,n)}(e,t,n)}const ut=new Map,pt={navigateTo:function(e,t,n=!1){ze(e,t instanceof Object?t:{forceLoad:t,replaceHistoryEntry:n})},registerCustomEventType:function(e,t){if(!t)throw new Error("The options parameter is required.");if(i.has(e))throw new Error(`The event '${e}' is already registered.`);if(t.browserEventName){const n=s.get(t.browserEventName);n?n.push(e):s.set(t.browserEventName,[e]),a.forEach((n=>n(e,t.browserEventName)))}i.set(e,t)},rootComponents:y,runtime:{},_internal:{navigationManager:We,domWrapper:et,Virtualize:tt,PageTitle:it,InputFile:st,NavigationLock:lt,getJSDataStreamChunk:dt,attachWebRendererInterop:function(t,n,o,r){if(S.has(t))throw new Error(`Interop methods are already registered for renderer ${t}`);S.set(t,n),Object.keys(o).length>0&&function(t,n,o){if(g)throw new Error("Dynamic root components have already been enabled.");g=t,m=n;for(const[t,r]of Object.entries(o)){const o=e.findJSFunction(t,0);for(const e of r)o(e,n[e])}}(D(t),o,r),I(),function(e){for(const t of C)t(e)}(t)}}};var ft;window.Blazor=pt,function(e){e[e.Trace=0]="Trace",e[e.Debug=1]="Debug",e[e.Information=2]="Information",e[e.Warning=3]="Warning",e[e.Error=4]="Error",e[e.Critical=5]="Critical",e[e.None=6]="None"}(ft||(ft={}));class gt{log(e,t){}}gt.instance=new gt;class mt{constructor(e){this.minLevel=e}log(e,t){if(e>=this.minLevel){const n=`[${(new Date).toISOString()}] ${ft[e]}: ${t}`;switch(e){case ft.Critical:case ft.Error:console.error(n);break;case ft.Warning:console.warn(n);break;case ft.Information:console.info(n);break;default:console.log(n)}}}}function vt(e,t){switch(t){case"webassembly":return Et(e,"webassembly");case"server":return function(e){return Et(e,"server").sort(((e,t)=>e.sequence-t.sequence))}(e);case"auto":return Et(e,"auto")}}const yt=/^\s*Blazor-Server-Component-State:(?[a-zA-Z0-9+/=]+)$/,wt=/^\s*Blazor-WebAssembly-Component-State:(?[a-zA-Z0-9+/=]+)$/;function bt(e){return _t(e,yt)}function _t(e,t){var n;if(e.nodeType===Node.COMMENT_NODE){const o=e.textContent||"",r=t.exec(o),i=r&&r.groups&&r.groups.state;return i&&(null===(n=e.parentNode)||void 0===n||n.removeChild(e)),i}if(!e.hasChildNodes())return;const o=e.childNodes;for(let e=0;e.*)$/);function Ct(e,t){const n=e.currentElement;var o,r,i;if(n&&n.nodeType===Node.COMMENT_NODE&&n.textContent){const s=St.exec(n.textContent),a=s&&s.groups&&s.groups.descriptor;if(!a)return;!function(e){if(e.parentNode instanceof Document)throw new Error("Root components cannot be marked as interactive. The element must be rendered statically so that scripts are not evaluated multiple times.")}(n);try{const s=function(e){const t=JSON.parse(e),{type:n}=t;if("server"!==n&&"webassembly"!==n&&"auto"!==n)throw new Error(`Invalid component type '${n}'.`);return t}(a),c=function(e,t,n){const{prerenderId:o}=e;if(o){for(;n.next()&&n.currentElement;){const e=n.currentElement;if(e.nodeType!==Node.COMMENT_NODE)continue;if(!e.textContent)continue;const t=St.exec(e.textContent),r=t&&t[1];if(r)return Dt(r,o),e}throw new Error(`Could not find an end component comment for '${t}'.`)}}(s,n,e);if(t!==s.type)return;switch(s.type){case"webassembly":return r=n,i=c,Tt(o=s),{...o,uniqueId:It++,start:r,end:i};case"server":return function(e,t,n){return kt(e),{...e,uniqueId:It++,start:t,end:n}}(s,n,c);case"auto":return function(e,t,n){return kt(e),Tt(e),{...e,uniqueId:It++,start:t,end:n}}(s,n,c)}}catch(e){throw new Error(`Found malformed component comment at ${n.textContent}`)}}}let It=0;function kt(e){const{descriptor:t,sequence:n}=e;if(!t)throw new Error("descriptor must be defined when using a descriptor.");if(void 0===n)throw new Error("sequence must be defined when using a descriptor.");if(!Number.isInteger(n))throw new Error(`Error parsing the sequence '${n}' for component '${JSON.stringify(e)}'`)}function Tt(e){const{assembly:t,typeName:n}=e;if(!t)throw new Error("assembly must be defined when using a descriptor.");if(!n)throw new Error("typeName must be defined when using a descriptor.");e.parameterDefinitions=e.parameterDefinitions&&atob(e.parameterDefinitions),e.parameterValues=e.parameterValues&&atob(e.parameterValues)}function Dt(e,t){const n=JSON.parse(e);if(1!==Object.keys(n).length)throw new Error(`Invalid end of component comment: '${e}'`);const o=n.prerenderId;if(!o)throw new Error(`End of component comment must have a value for the prerendered property: '${e}'`);if(o!==t)throw new Error(`End of component comment prerendered property must match the start comment prerender id: '${t}', '${o}'`)}class Rt{constructor(e){this.childNodes=e,this.currentIndex=-1,this.length=e.length}next(){return this.currentIndex++,this.currentIndex{n+=`0x${e<16?"0":""}${e.toString(16)} `})),n.substr(0,n.length-1)}(e)}'`)):"string"==typeof e&&(n=`String data of length ${e.length}`,t&&(n+=`. Content: '${e}'`)),n}function Ot(e){return e&&"undefined"!=typeof ArrayBuffer&&(e instanceof ArrayBuffer||e.constructor&&"ArrayBuffer"===e.constructor.name)}async function $t(e,t,n,o,r,i){const s={},[a,c]=Wt();s[a]=c,e.log(Mt.Trace,`(${t} transport) sending data. ${Ft(r,i.logMessageContent)}.`);const l=Ot(r)?"arraybuffer":"text",h=await n.post(o,{content:r,headers:{...s,...i.headers},responseType:l,timeout:i.timeout,withCredentials:i.withCredentials});e.log(Mt.Trace,`(${t} transport) request complete. Response status: ${h.statusCode}.`)}class Ht{constructor(e,t){this._subject=e,this._observer=t}dispose(){const e=this._subject.observers.indexOf(this._observer);e>-1&&this._subject.observers.splice(e,1),0===this._subject.observers.length&&this._subject.cancelCallback&&this._subject.cancelCallback().catch((e=>{}))}}class jt{constructor(e){this._minLevel=e,this.out=console}log(e,t){if(e>=this._minLevel){const n=`[${(new Date).toISOString()}] ${Mt[e]}: ${t}`;switch(e){case Mt.Critical:case Mt.Error:this.out.error(n);break;case Mt.Warning:this.out.warn(n);break;case Mt.Information:this.out.info(n);break;default:this.out.log(n)}}}}function Wt(){let e="X-SignalR-User-Agent";return Bt.isNode&&(e="User-Agent"),[e,qt(Ut,zt(),Bt.isNode?"NodeJS":"Browser",Jt())]}function qt(e,t,n,o){let r="Microsoft SignalR/";const i=e.split(".");return r+=`${i[0]}.${i[1]}`,r+=` (${e}; `,r+=t&&""!==t?`${t}; `:"Unknown OS; ",r+=`${n}`,r+=o?`; ${o}`:"; Unknown Runtime Version",r+=")",r}function zt(){if(!Bt.isNode)return"";switch(process.platform){case"win32":return"Windows NT";case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}}function Jt(){if(Bt.isNode)return process.versions.node}function Vt(e){return e.stack?e.stack:e.message?e.message:`${e}`}class Kt{writeHandshakeRequest(e){return Nt.write(JSON.stringify(e))}parseHandshakeResponse(e){let t,n;if(Ot(e)){const o=new Uint8Array(e),r=o.indexOf(Nt.RecordSeparatorCode);if(-1===r)throw new Error("Message is incomplete.");const i=r+1;t=String.fromCharCode.apply(null,Array.prototype.slice.call(o.slice(0,i))),n=o.byteLength>i?o.slice(i).buffer:null}else{const o=e,r=o.indexOf(Nt.RecordSeparator);if(-1===r)throw new Error("Message is incomplete.");const i=r+1;t=o.substring(0,i),n=o.length>i?o.substring(i):null}const o=Nt.parse(t),r=JSON.parse(o[0]);if(r.type)throw new Error("Expected a handshake response from the server.");return[n,r]}}class Xt extends Error{constructor(e,t){const n=new.target.prototype;super(`${e}: Status code '${t}'`),this.statusCode=t,this.__proto__=n}}class Gt extends Error{constructor(e="A timeout occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class Yt extends Error{constructor(e="An abort occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class Qt extends Error{constructor(e,t){const n=new.target.prototype;super(e),this.transport=t,this.errorType="UnsupportedTransportError",this.__proto__=n}}class Zt extends Error{constructor(e,t){const n=new.target.prototype;super(e),this.transport=t,this.errorType="DisabledTransportError",this.__proto__=n}}class en extends Error{constructor(e,t){const n=new.target.prototype;super(e),this.transport=t,this.errorType="FailedToStartTransportError",this.__proto__=n}}class tn extends Error{constructor(e){const t=new.target.prototype;super(e),this.errorType="FailedToNegotiateWithServerError",this.__proto__=t}}class nn extends Error{constructor(e,t){const n=new.target.prototype;super(e),this.innerErrors=t,this.__proto__=n}}var on,rn;!function(e){e[e.Invocation=1]="Invocation",e[e.StreamItem=2]="StreamItem",e[e.Completion=3]="Completion",e[e.StreamInvocation=4]="StreamInvocation",e[e.CancelInvocation=5]="CancelInvocation",e[e.Ping=6]="Ping",e[e.Close=7]="Close",e[e.Ack=8]="Ack",e[e.Sequence=9]="Sequence"}(on||(on={}));class sn{constructor(){this.observers=[]}next(e){for(const t of this.observers)t.next(e)}error(e){for(const t of this.observers)t.error&&t.error(e)}complete(){for(const e of this.observers)e.complete&&e.complete()}subscribe(e){return this.observers.push(e),new Ht(this,e)}}class an{constructor(e,t,n){this._bufferSize=1e5,this._messages=[],this._totalMessageCount=0,this._waitForSequenceMessage=!1,this._nextReceivingSequenceId=1,this._latestReceivedSequenceId=0,this._bufferedByteCount=0,this._reconnectInProgress=!1,this._protocol=e,this._connection=t,this._bufferSize=n}async _send(e){const t=this._protocol.writeMessage(e);let n=Promise.resolve();if(this._isInvocationMessage(e)){this._totalMessageCount++;let e=()=>{},o=()=>{};Ot(t)?this._bufferedByteCount+=t.byteLength:this._bufferedByteCount+=t.length,this._bufferedByteCount>=this._bufferSize&&(n=new Promise(((t,n)=>{e=t,o=n}))),this._messages.push(new cn(t,this._totalMessageCount,e,o))}try{this._reconnectInProgress||await this._connection.send(t)}catch{this._disconnected()}await n}_ack(e){let t=-1;for(let n=0;nthis._nextReceivingSequenceId?this._connection.stop(new Error("Sequence ID greater than amount of messages we've received.")):this._nextReceivingSequenceId=e.sequenceId}_disconnected(){this._reconnectInProgress=!0,this._waitForSequenceMessage=!0}async _resend(){const e=0!==this._messages.length?this._messages[0]._id:this._totalMessageCount+1;await this._connection.send(this._protocol.writeMessage({type:on.Sequence,sequenceId:e}));const t=this._messages;for(const e of t)await this._connection.send(e._message);this._reconnectInProgress=!1}_dispose(e){null!=e||(e=new Error("Unable to reconnect to server."));for(const t of this._messages)t._rejector(e)}_isInvocationMessage(e){switch(e.type){case on.Invocation:case on.StreamItem:case on.Completion:case on.StreamInvocation:case on.CancelInvocation:return!0;case on.Close:case on.Sequence:case on.Ping:case on.Ack:return!1}}_ackTimer(){void 0===this._ackTimerHandle&&(this._ackTimerHandle=setTimeout((async()=>{try{this._reconnectInProgress||await this._connection.send(this._protocol.writeMessage({type:on.Ack,sequenceId:this._latestReceivedSequenceId}))}catch{}clearTimeout(this._ackTimerHandle),this._ackTimerHandle=void 0}),1e3))}}class cn{constructor(e,t,n,o){this._message=e,this._id=t,this._resolver=n,this._rejector=o}}!function(e){e.Disconnected="Disconnected",e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Reconnecting="Reconnecting"}(rn||(rn={}));class ln{static create(e,t,n,o,r,i,s){return new ln(e,t,n,o,r,i,s)}constructor(e,t,n,o,r,i,s){this._nextKeepAlive=0,this._freezeEventListener=()=>{this._logger.log(Mt.Warning,"The page is being frozen, this will likely lead to the connection being closed and messages being lost. For more information see the docs at https://learn.microsoft.com/aspnet/core/signalr/javascript-client#bsleep")},Lt.isRequired(e,"connection"),Lt.isRequired(t,"logger"),Lt.isRequired(n,"protocol"),this.serverTimeoutInMilliseconds=null!=r?r:3e4,this.keepAliveIntervalInMilliseconds=null!=i?i:15e3,this._statefulReconnectBufferSize=null!=s?s:1e5,this._logger=t,this._protocol=n,this.connection=e,this._reconnectPolicy=o,this._handshakeProtocol=new Kt,this.connection.onreceive=e=>this._processIncomingData(e),this.connection.onclose=e=>this._connectionClosed(e),this._callbacks={},this._methods={},this._closedCallbacks=[],this._reconnectingCallbacks=[],this._reconnectedCallbacks=[],this._invocationId=0,this._receivedHandshakeResponse=!1,this._connectionState=rn.Disconnected,this._connectionStarted=!1,this._cachedPingMessage=this._protocol.writeMessage({type:on.Ping})}get state(){return this._connectionState}get connectionId(){return this.connection&&this.connection.connectionId||null}get baseUrl(){return this.connection.baseUrl||""}set baseUrl(e){if(this._connectionState!==rn.Disconnected&&this._connectionState!==rn.Reconnecting)throw new Error("The HubConnection must be in the Disconnected or Reconnecting state to change the url.");if(!e)throw new Error("The HubConnection url must be a valid url.");this.connection.baseUrl=e}start(){return this._startPromise=this._startWithStateTransitions(),this._startPromise}async _startWithStateTransitions(){if(this._connectionState!==rn.Disconnected)return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."));this._connectionState=rn.Connecting,this._logger.log(Mt.Debug,"Starting HubConnection.");try{await this._startInternal(),Bt.isBrowser&&window.document.addEventListener("freeze",this._freezeEventListener),this._connectionState=rn.Connected,this._connectionStarted=!0,this._logger.log(Mt.Debug,"HubConnection connected successfully.")}catch(e){return this._connectionState=rn.Disconnected,this._logger.log(Mt.Debug,`HubConnection failed to start successfully because of error '${e}'.`),Promise.reject(e)}}async _startInternal(){this._stopDuringStartError=void 0,this._receivedHandshakeResponse=!1;const e=new Promise(((e,t)=>{this._handshakeResolver=e,this._handshakeRejecter=t}));await this.connection.start(this._protocol.transferFormat);try{let t=this._protocol.version;this.connection.features.reconnect||(t=1);const n={protocol:this._protocol.name,version:t};if(this._logger.log(Mt.Debug,"Sending handshake request."),await this._sendMessage(this._handshakeProtocol.writeHandshakeRequest(n)),this._logger.log(Mt.Information,`Using HubProtocol '${this._protocol.name}'.`),this._cleanupTimeout(),this._resetTimeoutPeriod(),this._resetKeepAliveInterval(),await e,this._stopDuringStartError)throw this._stopDuringStartError;!!this.connection.features.reconnect&&(this._messageBuffer=new an(this._protocol,this.connection,this._statefulReconnectBufferSize),this.connection.features.disconnected=this._messageBuffer._disconnected.bind(this._messageBuffer),this.connection.features.resend=()=>{if(this._messageBuffer)return this._messageBuffer._resend()}),this.connection.features.inherentKeepAlive||await this._sendMessage(this._cachedPingMessage)}catch(e){throw this._logger.log(Mt.Debug,`Hub handshake failed with error '${e}' during start(). Stopping HubConnection.`),this._cleanupTimeout(),this._cleanupPingTimer(),await this.connection.stop(e),e}}async stop(){const e=this._startPromise;this.connection.features.reconnect=!1,this._stopPromise=this._stopInternal(),await this._stopPromise;try{await e}catch(e){}}_stopInternal(e){if(this._connectionState===rn.Disconnected)return this._logger.log(Mt.Debug,`Call to HubConnection.stop(${e}) ignored because it is already in the disconnected state.`),Promise.resolve();if(this._connectionState===rn.Disconnecting)return this._logger.log(Mt.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnecting state.`),this._stopPromise;const t=this._connectionState;return this._connectionState=rn.Disconnecting,this._logger.log(Mt.Debug,"Stopping HubConnection."),this._reconnectDelayHandle?(this._logger.log(Mt.Debug,"Connection stopped during reconnect delay. Done reconnecting."),clearTimeout(this._reconnectDelayHandle),this._reconnectDelayHandle=void 0,this._completeClose(),Promise.resolve()):(t===rn.Connected&&this._sendCloseMessage(),this._cleanupTimeout(),this._cleanupPingTimer(),this._stopDuringStartError=e||new Yt("The connection was stopped before the hub handshake could complete."),this.connection.stop(e))}async _sendCloseMessage(){try{await this._sendWithProtocol(this._createCloseMessage())}catch{}}stream(e,...t){const[n,o]=this._replaceStreamingParams(t),r=this._createStreamInvocation(e,t,o);let i;const s=new sn;return s.cancelCallback=()=>{const e=this._createCancelInvocation(r.invocationId);return delete this._callbacks[r.invocationId],i.then((()=>this._sendWithProtocol(e)))},this._callbacks[r.invocationId]=(e,t)=>{t?s.error(t):e&&(e.type===on.Completion?e.error?s.error(new Error(e.error)):s.complete():s.next(e.item))},i=this._sendWithProtocol(r).catch((e=>{s.error(e),delete this._callbacks[r.invocationId]})),this._launchStreams(n,i),s}_sendMessage(e){return this._resetKeepAliveInterval(),this.connection.send(e)}_sendWithProtocol(e){return this._messageBuffer?this._messageBuffer._send(e):this._sendMessage(this._protocol.writeMessage(e))}send(e,...t){const[n,o]=this._replaceStreamingParams(t),r=this._sendWithProtocol(this._createInvocation(e,t,!0,o));return this._launchStreams(n,r),r}invoke(e,...t){const[n,o]=this._replaceStreamingParams(t),r=this._createInvocation(e,t,!1,o);return new Promise(((e,t)=>{this._callbacks[r.invocationId]=(n,o)=>{o?t(o):n&&(n.type===on.Completion?n.error?t(new Error(n.error)):e(n.result):t(new Error(`Unexpected message type: ${n.type}`)))};const o=this._sendWithProtocol(r).catch((e=>{t(e),delete this._callbacks[r.invocationId]}));this._launchStreams(n,o)}))}on(e,t){e&&t&&(e=e.toLowerCase(),this._methods[e]||(this._methods[e]=[]),-1===this._methods[e].indexOf(t)&&this._methods[e].push(t))}off(e,t){if(!e)return;e=e.toLowerCase();const n=this._methods[e];if(n)if(t){const o=n.indexOf(t);-1!==o&&(n.splice(o,1),0===n.length&&delete this._methods[e])}else delete this._methods[e]}onclose(e){e&&this._closedCallbacks.push(e)}onreconnecting(e){e&&this._reconnectingCallbacks.push(e)}onreconnected(e){e&&this._reconnectedCallbacks.push(e)}_processIncomingData(e){if(this._cleanupTimeout(),this._receivedHandshakeResponse||(e=this._processHandshakeResponse(e),this._receivedHandshakeResponse=!0),e){const t=this._protocol.parseMessages(e,this._logger);for(const e of t)if(!this._messageBuffer||this._messageBuffer._shouldProcessMessage(e))switch(e.type){case on.Invocation:this._invokeClientMethod(e);break;case on.StreamItem:case on.Completion:{const t=this._callbacks[e.invocationId];if(t){e.type===on.Completion&&delete this._callbacks[e.invocationId];try{t(e)}catch(e){this._logger.log(Mt.Error,`Stream callback threw error: ${Vt(e)}`)}}break}case on.Ping:break;case on.Close:{this._logger.log(Mt.Information,"Close message received from server.");const t=e.error?new Error("Server returned an error on close: "+e.error):void 0;!0===e.allowReconnect?this.connection.stop(t):this._stopPromise=this._stopInternal(t);break}case on.Ack:this._messageBuffer&&this._messageBuffer._ack(e);break;case on.Sequence:this._messageBuffer&&this._messageBuffer._resetSequence(e);break;default:this._logger.log(Mt.Warning,`Invalid message type: ${e.type}.`)}}this._resetTimeoutPeriod()}_processHandshakeResponse(e){let t,n;try{[n,t]=this._handshakeProtocol.parseHandshakeResponse(e)}catch(e){const t="Error parsing handshake response: "+e;this._logger.log(Mt.Error,t);const n=new Error(t);throw this._handshakeRejecter(n),n}if(t.error){const e="Server returned handshake error: "+t.error;this._logger.log(Mt.Error,e);const n=new Error(e);throw this._handshakeRejecter(n),n}return this._logger.log(Mt.Debug,"Server handshake complete."),this._handshakeResolver(),n}_resetKeepAliveInterval(){this.connection.features.inherentKeepAlive||(this._nextKeepAlive=(new Date).getTime()+this.keepAliveIntervalInMilliseconds,this._cleanupPingTimer())}_resetTimeoutPeriod(){if(!(this.connection.features&&this.connection.features.inherentKeepAlive||(this._timeoutHandle=setTimeout((()=>this.serverTimeout()),this.serverTimeoutInMilliseconds),void 0!==this._pingServerHandle))){let e=this._nextKeepAlive-(new Date).getTime();e<0&&(e=0),this._pingServerHandle=setTimeout((async()=>{if(this._connectionState===rn.Connected)try{await this._sendMessage(this._cachedPingMessage)}catch{this._cleanupPingTimer()}}),e)}}serverTimeout(){this.connection.stop(new Error("Server timeout elapsed without receiving a message from the server."))}async _invokeClientMethod(e){const t=e.target.toLowerCase(),n=this._methods[t];if(!n)return this._logger.log(Mt.Warning,`No client method with the name '${t}' found.`),void(e.invocationId&&(this._logger.log(Mt.Warning,`No result given for '${t}' method and invocation ID '${e.invocationId}'.`),await this._sendWithProtocol(this._createCompletionMessage(e.invocationId,"Client didn't provide a result.",null))));const o=n.slice(),r=!!e.invocationId;let i,s,a;for(const n of o)try{const o=i;i=await n.apply(this,e.arguments),r&&i&&o&&(this._logger.log(Mt.Error,`Multiple results provided for '${t}'. Sending error to server.`),a=this._createCompletionMessage(e.invocationId,"Client provided multiple results.",null)),s=void 0}catch(e){s=e,this._logger.log(Mt.Error,`A callback for the method '${t}' threw error '${e}'.`)}a?await this._sendWithProtocol(a):r?(s?a=this._createCompletionMessage(e.invocationId,`${s}`,null):void 0!==i?a=this._createCompletionMessage(e.invocationId,null,i):(this._logger.log(Mt.Warning,`No result given for '${t}' method and invocation ID '${e.invocationId}'.`),a=this._createCompletionMessage(e.invocationId,"Client didn't provide a result.",null)),await this._sendWithProtocol(a)):i&&this._logger.log(Mt.Error,`Result given for '${t}' method but server is not expecting a result.`)}_connectionClosed(e){this._logger.log(Mt.Debug,`HubConnection.connectionClosed(${e}) called while in state ${this._connectionState}.`),this._stopDuringStartError=this._stopDuringStartError||e||new Yt("The underlying connection was closed before the hub handshake could complete."),this._handshakeResolver&&this._handshakeResolver(),this._cancelCallbacksWithError(e||new Error("Invocation canceled due to the underlying connection being closed.")),this._cleanupTimeout(),this._cleanupPingTimer(),this._connectionState===rn.Disconnecting?this._completeClose(e):this._connectionState===rn.Connected&&this._reconnectPolicy?this._reconnect(e):this._connectionState===rn.Connected&&this._completeClose(e)}_completeClose(e){if(this._connectionStarted){this._connectionState=rn.Disconnected,this._connectionStarted=!1,this._messageBuffer&&(this._messageBuffer._dispose(null!=e?e:new Error("Connection closed.")),this._messageBuffer=void 0),Bt.isBrowser&&window.document.removeEventListener("freeze",this._freezeEventListener);try{this._closedCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(Mt.Error,`An onclose callback called with error '${e}' threw error '${t}'.`)}}}async _reconnect(e){const t=Date.now();let n=0,o=void 0!==e?e:new Error("Attempting to reconnect due to a unknown error."),r=this._getNextRetryDelay(n++,0,o);if(null===r)return this._logger.log(Mt.Debug,"Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt."),void this._completeClose(e);if(this._connectionState=rn.Reconnecting,e?this._logger.log(Mt.Information,`Connection reconnecting because of error '${e}'.`):this._logger.log(Mt.Information,"Connection reconnecting."),0!==this._reconnectingCallbacks.length){try{this._reconnectingCallbacks.forEach((t=>t.apply(this,[e])))}catch(t){this._logger.log(Mt.Error,`An onreconnecting callback called with error '${e}' threw error '${t}'.`)}if(this._connectionState!==rn.Reconnecting)return void this._logger.log(Mt.Debug,"Connection left the reconnecting state in onreconnecting callback. Done reconnecting.")}for(;null!==r;){if(this._logger.log(Mt.Information,`Reconnect attempt number ${n} will start in ${r} ms.`),await new Promise((e=>{this._reconnectDelayHandle=setTimeout(e,r)})),this._reconnectDelayHandle=void 0,this._connectionState!==rn.Reconnecting)return void this._logger.log(Mt.Debug,"Connection left the reconnecting state during reconnect delay. Done reconnecting.");try{if(await this._startInternal(),this._connectionState=rn.Connected,this._logger.log(Mt.Information,"HubConnection reconnected successfully."),0!==this._reconnectedCallbacks.length)try{this._reconnectedCallbacks.forEach((e=>e.apply(this,[this.connection.connectionId])))}catch(e){this._logger.log(Mt.Error,`An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${e}'.`)}return}catch(e){if(this._logger.log(Mt.Information,`Reconnect attempt failed because of error '${e}'.`),this._connectionState!==rn.Reconnecting)return this._logger.log(Mt.Debug,`Connection moved to the '${this._connectionState}' from the reconnecting state during reconnect attempt. Done reconnecting.`),void(this._connectionState===rn.Disconnecting&&this._completeClose());o=e instanceof Error?e:new Error(e.toString()),r=this._getNextRetryDelay(n++,Date.now()-t,o)}}this._logger.log(Mt.Information,`Reconnect retries have been exhausted after ${Date.now()-t} ms and ${n} failed attempts. Connection disconnecting.`),this._completeClose()}_getNextRetryDelay(e,t,n){try{return this._reconnectPolicy.nextRetryDelayInMilliseconds({elapsedMilliseconds:t,previousRetryCount:e,retryReason:n})}catch(n){return this._logger.log(Mt.Error,`IRetryPolicy.nextRetryDelayInMilliseconds(${e}, ${t}) threw error '${n}'.`),null}}_cancelCallbacksWithError(e){const t=this._callbacks;this._callbacks={},Object.keys(t).forEach((n=>{const o=t[n];try{o(null,e)}catch(t){this._logger.log(Mt.Error,`Stream 'error' callback called with '${e}' threw error: ${Vt(t)}`)}}))}_cleanupPingTimer(){this._pingServerHandle&&(clearTimeout(this._pingServerHandle),this._pingServerHandle=void 0)}_cleanupTimeout(){this._timeoutHandle&&clearTimeout(this._timeoutHandle)}_createInvocation(e,t,n,o){if(n)return 0!==o.length?{arguments:t,streamIds:o,target:e,type:on.Invocation}:{arguments:t,target:e,type:on.Invocation};{const n=this._invocationId;return this._invocationId++,0!==o.length?{arguments:t,invocationId:n.toString(),streamIds:o,target:e,type:on.Invocation}:{arguments:t,invocationId:n.toString(),target:e,type:on.Invocation}}}_launchStreams(e,t){if(0!==e.length){t||(t=Promise.resolve());for(const n in e)e[n].subscribe({complete:()=>{t=t.then((()=>this._sendWithProtocol(this._createCompletionMessage(n))))},error:e=>{let o;o=e instanceof Error?e.message:e&&e.toString?e.toString():"Unknown error",t=t.then((()=>this._sendWithProtocol(this._createCompletionMessage(n,o))))},next:e=>{t=t.then((()=>this._sendWithProtocol(this._createStreamItemMessage(n,e))))}})}}_replaceStreamingParams(e){const t=[],n=[];for(let o=0;o0)&&(t=!1,this._accessToken=await this._accessTokenFactory()),this._setAuthorizationHeader(e);const n=await this._innerClient.send(e);return t&&401===n.statusCode&&this._accessTokenFactory?(this._accessToken=await this._accessTokenFactory(),this._setAuthorizationHeader(e),await this._innerClient.send(e)):n}_setAuthorizationHeader(e){e.headers||(e.headers={}),this._accessToken?e.headers[un.Authorization]=`Bearer ${this._accessToken}`:this._accessTokenFactory&&e.headers[un.Authorization]&&delete e.headers[un.Authorization]}getCookieString(e){return this._innerClient.getCookieString(e)}}class mn extends fn{constructor(e){super(),this._logger=e;const t={_fetchType:void 0,_jar:void 0};var o;o=t,"undefined"==typeof fetch&&(o._jar=new(n(628).CookieJar),"undefined"==typeof fetch?o._fetchType=n(200):o._fetchType=fetch,o._fetchType=n(203)(o._fetchType,o._jar),1)?(this._fetchType=t._fetchType,this._jar=t._jar):this._fetchType=fetch.bind(function(){if("undefined"!=typeof globalThis)return globalThis;if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if(void 0!==n.g)return n.g;throw new Error("could not find global")}()),this._abortControllerType=AbortController;const r={_abortControllerType:this._abortControllerType};(function(e){return"undefined"==typeof AbortController&&(e._abortControllerType=n(778),!0)})(r)&&(this._abortControllerType=r._abortControllerType)}async send(e){if(e.abortSignal&&e.abortSignal.aborted)throw new Yt;if(!e.method)throw new Error("No method defined.");if(!e.url)throw new Error("No url defined.");const t=new this._abortControllerType;let n;e.abortSignal&&(e.abortSignal.onabort=()=>{t.abort(),n=new Yt});let o,r=null;if(e.timeout){const o=e.timeout;r=setTimeout((()=>{t.abort(),this._logger.log(Mt.Warning,"Timeout from HTTP request."),n=new Gt}),o)}""===e.content&&(e.content=void 0),e.content&&(e.headers=e.headers||{},Ot(e.content)?e.headers["Content-Type"]="application/octet-stream":e.headers["Content-Type"]="text/plain;charset=UTF-8");try{o=await this._fetchType(e.url,{body:e.content,cache:"no-cache",credentials:!0===e.withCredentials?"include":"same-origin",headers:{"X-Requested-With":"XMLHttpRequest",...e.headers},method:e.method,mode:"cors",redirect:"follow",signal:t.signal})}catch(e){if(n)throw n;throw this._logger.log(Mt.Warning,`Error from HTTP request. ${e}.`),e}finally{r&&clearTimeout(r),e.abortSignal&&(e.abortSignal.onabort=null)}if(!o.ok){const e=await vn(o,"text");throw new Xt(e||o.statusText,o.status)}const i=vn(o,e.responseType),s=await i;return new pn(o.status,o.statusText,s)}getCookieString(e){return""}}function vn(e,t){let n;switch(t){case"arraybuffer":n=e.arrayBuffer();break;case"text":default:n=e.text();break;case"blob":case"document":case"json":throw new Error(`${t} is not supported.`)}return n}class yn extends fn{constructor(e){super(),this._logger=e}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new Yt):e.method?e.url?new Promise(((t,n)=>{const o=new XMLHttpRequest;o.open(e.method,e.url,!0),o.withCredentials=void 0===e.withCredentials||e.withCredentials,o.setRequestHeader("X-Requested-With","XMLHttpRequest"),""===e.content&&(e.content=void 0),e.content&&(Ot(e.content)?o.setRequestHeader("Content-Type","application/octet-stream"):o.setRequestHeader("Content-Type","text/plain;charset=UTF-8"));const r=e.headers;r&&Object.keys(r).forEach((e=>{o.setRequestHeader(e,r[e])})),e.responseType&&(o.responseType=e.responseType),e.abortSignal&&(e.abortSignal.onabort=()=>{o.abort(),n(new Yt)}),e.timeout&&(o.timeout=e.timeout),o.onload=()=>{e.abortSignal&&(e.abortSignal.onabort=null),o.status>=200&&o.status<300?t(new pn(o.status,o.statusText,o.response||o.responseText)):n(new Xt(o.response||o.responseText||o.statusText,o.status))},o.onerror=()=>{this._logger.log(Mt.Warning,`Error from HTTP request. ${o.status}: ${o.statusText}.`),n(new Xt(o.statusText,o.status))},o.ontimeout=()=>{this._logger.log(Mt.Warning,"Timeout from HTTP request."),n(new Gt)},o.send(e.content)})):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}}class wn extends fn{constructor(e){if(super(),"undefined"!=typeof fetch)this._httpClient=new mn(e);else{if("undefined"==typeof XMLHttpRequest)throw new Error("No usable HttpClient found.");this._httpClient=new yn(e)}}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new Yt):e.method?e.url?this._httpClient.send(e):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}getCookieString(e){return this._httpClient.getCookieString(e)}}var bn,_n;!function(e){e[e.None=0]="None",e[e.WebSockets=1]="WebSockets",e[e.ServerSentEvents=2]="ServerSentEvents",e[e.LongPolling=4]="LongPolling"}(bn||(bn={})),function(e){e[e.Text=1]="Text",e[e.Binary=2]="Binary"}(_n||(_n={}));class En{constructor(){this._isAborted=!1,this.onabort=null}abort(){this._isAborted||(this._isAborted=!0,this.onabort&&this.onabort())}get signal(){return this}get aborted(){return this._isAborted}}class Sn{get pollAborted(){return this._pollAbort.aborted}constructor(e,t,n){this._httpClient=e,this._logger=t,this._pollAbort=new En,this._options=n,this._running=!1,this.onreceive=null,this.onclose=null}async connect(e,t){if(Lt.isRequired(e,"url"),Lt.isRequired(t,"transferFormat"),Lt.isIn(t,_n,"transferFormat"),this._url=e,this._logger.log(Mt.Trace,"(LongPolling transport) Connecting."),t===_n.Binary&&"undefined"!=typeof XMLHttpRequest&&"string"!=typeof(new XMLHttpRequest).responseType)throw new Error("Binary protocols over XmlHttpRequest not implementing advanced features are not supported.");const[n,o]=Wt(),r={[n]:o,...this._options.headers},i={abortSignal:this._pollAbort.signal,headers:r,timeout:1e5,withCredentials:this._options.withCredentials};t===_n.Binary&&(i.responseType="arraybuffer");const s=`${e}&_=${Date.now()}`;this._logger.log(Mt.Trace,`(LongPolling transport) polling: ${s}.`);const a=await this._httpClient.get(s,i);200!==a.statusCode?(this._logger.log(Mt.Error,`(LongPolling transport) Unexpected response code: ${a.statusCode}.`),this._closeError=new Xt(a.statusText||"",a.statusCode),this._running=!1):this._running=!0,this._receiving=this._poll(this._url,i)}async _poll(e,t){try{for(;this._running;)try{const n=`${e}&_=${Date.now()}`;this._logger.log(Mt.Trace,`(LongPolling transport) polling: ${n}.`);const o=await this._httpClient.get(n,t);204===o.statusCode?(this._logger.log(Mt.Information,"(LongPolling transport) Poll terminated by server."),this._running=!1):200!==o.statusCode?(this._logger.log(Mt.Error,`(LongPolling transport) Unexpected response code: ${o.statusCode}.`),this._closeError=new Xt(o.statusText||"",o.statusCode),this._running=!1):o.content?(this._logger.log(Mt.Trace,`(LongPolling transport) data received. ${Ft(o.content,this._options.logMessageContent)}.`),this.onreceive&&this.onreceive(o.content)):this._logger.log(Mt.Trace,"(LongPolling transport) Poll timed out, reissuing.")}catch(e){this._running?e instanceof Gt?this._logger.log(Mt.Trace,"(LongPolling transport) Poll timed out, reissuing."):(this._closeError=e,this._running=!1):this._logger.log(Mt.Trace,`(LongPolling transport) Poll errored after shutdown: ${e.message}`)}}finally{this._logger.log(Mt.Trace,"(LongPolling transport) Polling complete."),this.pollAborted||this._raiseOnClose()}}async send(e){return this._running?$t(this._logger,"LongPolling",this._httpClient,this._url,e,this._options):Promise.reject(new Error("Cannot send until the transport is connected"))}async stop(){this._logger.log(Mt.Trace,"(LongPolling transport) Stopping polling."),this._running=!1,this._pollAbort.abort();try{await this._receiving,this._logger.log(Mt.Trace,`(LongPolling transport) sending DELETE request to ${this._url}.`);const e={},[t,n]=Wt();e[t]=n;const o={headers:{...e,...this._options.headers},timeout:this._options.timeout,withCredentials:this._options.withCredentials};let r;try{await this._httpClient.delete(this._url,o)}catch(e){r=e}r?r instanceof Xt&&(404===r.statusCode?this._logger.log(Mt.Trace,"(LongPolling transport) A 404 response was returned from sending a DELETE request."):this._logger.log(Mt.Trace,`(LongPolling transport) Error sending a DELETE request: ${r}`)):this._logger.log(Mt.Trace,"(LongPolling transport) DELETE request accepted.")}finally{this._logger.log(Mt.Trace,"(LongPolling transport) Stop finished."),this._raiseOnClose()}}_raiseOnClose(){if(this.onclose){let e="(LongPolling transport) Firing onclose event.";this._closeError&&(e+=" Error: "+this._closeError),this._logger.log(Mt.Trace,e),this.onclose(this._closeError)}}}class Cn{constructor(e,t,n,o){this._httpClient=e,this._accessToken=t,this._logger=n,this._options=o,this.onreceive=null,this.onclose=null}async connect(e,t){return Lt.isRequired(e,"url"),Lt.isRequired(t,"transferFormat"),Lt.isIn(t,_n,"transferFormat"),this._logger.log(Mt.Trace,"(SSE transport) Connecting."),this._url=e,this._accessToken&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(this._accessToken)}`),new Promise(((n,o)=>{let r,i=!1;if(t===_n.Text){if(Bt.isBrowser||Bt.isWebWorker)r=new this._options.EventSource(e,{withCredentials:this._options.withCredentials});else{const t=this._httpClient.getCookieString(e),n={};n.Cookie=t;const[o,i]=Wt();n[o]=i,r=new this._options.EventSource(e,{withCredentials:this._options.withCredentials,headers:{...n,...this._options.headers}})}try{r.onmessage=e=>{if(this.onreceive)try{this._logger.log(Mt.Trace,`(SSE transport) data received. ${Ft(e.data,this._options.logMessageContent)}.`),this.onreceive(e.data)}catch(e){return void this._close(e)}},r.onerror=e=>{i?this._close():o(new Error("EventSource failed to connect. The connection could not be found on the server, either the connection ID is not present on the server, or a proxy is refusing/buffering the connection. If you have multiple servers check that sticky sessions are enabled."))},r.onopen=()=>{this._logger.log(Mt.Information,`SSE connected to ${this._url}`),this._eventSource=r,i=!0,n()}}catch(e){return void o(e)}}else o(new Error("The Server-Sent Events transport only supports the 'Text' transfer format"))}))}async send(e){return this._eventSource?$t(this._logger,"SSE",this._httpClient,this._url,e,this._options):Promise.reject(new Error("Cannot send until the transport is connected"))}stop(){return this._close(),Promise.resolve()}_close(e){this._eventSource&&(this._eventSource.close(),this._eventSource=void 0,this.onclose&&this.onclose(e))}}class In{constructor(e,t,n,o,r,i){this._logger=n,this._accessTokenFactory=t,this._logMessageContent=o,this._webSocketConstructor=r,this._httpClient=e,this.onreceive=null,this.onclose=null,this._headers=i}async connect(e,t){let n;return Lt.isRequired(e,"url"),Lt.isRequired(t,"transferFormat"),Lt.isIn(t,_n,"transferFormat"),this._logger.log(Mt.Trace,"(WebSockets transport) Connecting."),this._accessTokenFactory&&(n=await this._accessTokenFactory()),new Promise(((o,r)=>{let i;e=e.replace(/^http/,"ws");const s=this._httpClient.getCookieString(e);let a=!1;if(Bt.isReactNative){const t={},[o,r]=Wt();t[o]=r,n&&(t[un.Authorization]=`Bearer ${n}`),s&&(t[un.Cookie]=s),i=new this._webSocketConstructor(e,void 0,{headers:{...t,...this._headers}})}else n&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(n)}`);i||(i=new this._webSocketConstructor(e)),t===_n.Binary&&(i.binaryType="arraybuffer"),i.onopen=t=>{this._logger.log(Mt.Information,`WebSocket connected to ${e}.`),this._webSocket=i,a=!0,o()},i.onerror=e=>{let t=null;t="undefined"!=typeof ErrorEvent&&e instanceof ErrorEvent?e.error:"There was an error with the transport",this._logger.log(Mt.Information,`(WebSockets transport) ${t}.`)},i.onmessage=e=>{if(this._logger.log(Mt.Trace,`(WebSockets transport) data received. ${Ft(e.data,this._logMessageContent)}.`),this.onreceive)try{this.onreceive(e.data)}catch(e){return void this._close(e)}},i.onclose=e=>{if(a)this._close(e);else{let t=null;t="undefined"!=typeof ErrorEvent&&e instanceof ErrorEvent?e.error:"WebSocket failed to connect. The connection could not be found on the server, either the endpoint may not be a SignalR endpoint, the connection ID is not present on the server, or there is a proxy blocking WebSockets. If you have multiple servers check that sticky sessions are enabled.",r(new Error(t))}}}))}send(e){return this._webSocket&&this._webSocket.readyState===this._webSocketConstructor.OPEN?(this._logger.log(Mt.Trace,`(WebSockets transport) sending data. ${Ft(e,this._logMessageContent)}.`),this._webSocket.send(e),Promise.resolve()):Promise.reject("WebSocket is not in the OPEN state")}stop(){return this._webSocket&&this._close(void 0),Promise.resolve()}_close(e){this._webSocket&&(this._webSocket.onclose=()=>{},this._webSocket.onmessage=()=>{},this._webSocket.onerror=()=>{},this._webSocket.close(),this._webSocket=void 0),this._logger.log(Mt.Trace,"(WebSockets transport) socket closed."),this.onclose&&(!this._isCloseEvent(e)||!1!==e.wasClean&&1e3===e.code?e instanceof Error?this.onclose(e):this.onclose():this.onclose(new Error(`WebSocket closed with status code: ${e.code} (${e.reason||"no reason given"}).`)))}_isCloseEvent(e){return e&&"boolean"==typeof e.wasClean&&"number"==typeof e.code}}class kn{constructor(e,t={}){if(this._stopPromiseResolver=()=>{},this.features={},this._negotiateVersion=1,Lt.isRequired(e,"url"),this._logger=function(e){return void 0===e?new jt(Mt.Information):null===e?Pt.instance:void 0!==e.log?e:new jt(e)}(t.logger),this.baseUrl=this._resolveUrl(e),(t=t||{}).logMessageContent=void 0!==t.logMessageContent&&t.logMessageContent,"boolean"!=typeof t.withCredentials&&void 0!==t.withCredentials)throw new Error("withCredentials option was not a 'boolean' or 'undefined' value");t.withCredentials=void 0===t.withCredentials||t.withCredentials,t.timeout=void 0===t.timeout?1e5:t.timeout,"undefined"==typeof WebSocket||t.WebSocket||(t.WebSocket=WebSocket),"undefined"==typeof EventSource||t.EventSource||(t.EventSource=EventSource),this._httpClient=new gn(t.httpClient||new wn(this._logger),t.accessTokenFactory),this._connectionState="Disconnected",this._connectionStarted=!1,this._options=t,this.onreceive=null,this.onclose=null}async start(e){if(e=e||_n.Binary,Lt.isIn(e,_n,"transferFormat"),this._logger.log(Mt.Debug,`Starting connection with transfer format '${_n[e]}'.`),"Disconnected"!==this._connectionState)return Promise.reject(new Error("Cannot start an HttpConnection that is not in the 'Disconnected' state."));if(this._connectionState="Connecting",this._startInternalPromise=this._startInternal(e),await this._startInternalPromise,"Disconnecting"===this._connectionState){const e="Failed to start the HttpConnection before stop() was called.";return this._logger.log(Mt.Error,e),await this._stopPromise,Promise.reject(new Yt(e))}if("Connected"!==this._connectionState){const e="HttpConnection.startInternal completed gracefully but didn't enter the connection into the connected state!";return this._logger.log(Mt.Error,e),Promise.reject(new Yt(e))}this._connectionStarted=!0}send(e){return"Connected"!==this._connectionState?Promise.reject(new Error("Cannot send data if the connection is not in the 'Connected' State.")):(this._sendQueue||(this._sendQueue=new Tn(this.transport)),this._sendQueue.send(e))}async stop(e){return"Disconnected"===this._connectionState?(this._logger.log(Mt.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnected state.`),Promise.resolve()):"Disconnecting"===this._connectionState?(this._logger.log(Mt.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnecting state.`),this._stopPromise):(this._connectionState="Disconnecting",this._stopPromise=new Promise((e=>{this._stopPromiseResolver=e})),await this._stopInternal(e),void await this._stopPromise)}async _stopInternal(e){this._stopError=e;try{await this._startInternalPromise}catch(e){}if(this.transport){try{await this.transport.stop()}catch(e){this._logger.log(Mt.Error,`HttpConnection.transport.stop() threw error '${e}'.`),this._stopConnection()}this.transport=void 0}else this._logger.log(Mt.Debug,"HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.")}async _startInternal(e){let t=this.baseUrl;this._accessTokenFactory=this._options.accessTokenFactory,this._httpClient._accessTokenFactory=this._accessTokenFactory;try{if(this._options.skipNegotiation){if(this._options.transport!==bn.WebSockets)throw new Error("Negotiation can only be skipped when using the WebSocket transport directly.");this.transport=this._constructTransport(bn.WebSockets),await this._startTransport(t,e)}else{let n=null,o=0;do{if(n=await this._getNegotiationResponse(t),"Disconnecting"===this._connectionState||"Disconnected"===this._connectionState)throw new Yt("The connection was stopped during negotiation.");if(n.error)throw new Error(n.error);if(n.ProtocolVersion)throw new Error("Detected a connection attempt to an ASP.NET SignalR Server. This client only supports connecting to an ASP.NET Core SignalR Server. See https://aka.ms/signalr-core-differences for details.");if(n.url&&(t=n.url),n.accessToken){const e=n.accessToken;this._accessTokenFactory=()=>e,this._httpClient._accessToken=e,this._httpClient._accessTokenFactory=void 0}o++}while(n.url&&o<100);if(100===o&&n.url)throw new Error("Negotiate redirection limit exceeded.");await this._createTransport(t,this._options.transport,n,e)}this.transport instanceof Sn&&(this.features.inherentKeepAlive=!0),"Connecting"===this._connectionState&&(this._logger.log(Mt.Debug,"The HttpConnection connected successfully."),this._connectionState="Connected")}catch(e){return this._logger.log(Mt.Error,"Failed to start the connection: "+e),this._connectionState="Disconnected",this.transport=void 0,this._stopPromiseResolver(),Promise.reject(e)}}async _getNegotiationResponse(e){const t={},[n,o]=Wt();t[n]=o;const r=this._resolveNegotiateUrl(e);this._logger.log(Mt.Debug,`Sending negotiation request: ${r}.`);try{const e=await this._httpClient.post(r,{content:"",headers:{...t,...this._options.headers},timeout:this._options.timeout,withCredentials:this._options.withCredentials});if(200!==e.statusCode)return Promise.reject(new Error(`Unexpected status code returned from negotiate '${e.statusCode}'`));const n=JSON.parse(e.content);return(!n.negotiateVersion||n.negotiateVersion<1)&&(n.connectionToken=n.connectionId),n.useStatefulReconnect&&!0!==this._options._useStatefulReconnect?Promise.reject(new tn("Client didn't negotiate Stateful Reconnect but the server did.")):n}catch(e){let t="Failed to complete negotiation with the server: "+e;return e instanceof Xt&&404===e.statusCode&&(t+=" Either this is not a SignalR endpoint or there is a proxy blocking the connection."),this._logger.log(Mt.Error,t),Promise.reject(new tn(t))}}_createConnectUrl(e,t){return t?e+(-1===e.indexOf("?")?"?":"&")+`id=${t}`:e}async _createTransport(e,t,n,o){let r=this._createConnectUrl(e,n.connectionToken);if(this._isITransport(t))return this._logger.log(Mt.Debug,"Connection was provided an instance of ITransport, using that directly."),this.transport=t,await this._startTransport(r,o),void(this.connectionId=n.connectionId);const i=[],s=n.availableTransports||[];let a=n;for(const n of s){const s=this._resolveTransportOrError(n,t,o,!0===(null==a?void 0:a.useStatefulReconnect));if(s instanceof Error)i.push(`${n.transport} failed:`),i.push(s);else if(this._isITransport(s)){if(this.transport=s,!a){try{a=await this._getNegotiationResponse(e)}catch(e){return Promise.reject(e)}r=this._createConnectUrl(e,a.connectionToken)}try{return await this._startTransport(r,o),void(this.connectionId=a.connectionId)}catch(e){if(this._logger.log(Mt.Error,`Failed to start the transport '${n.transport}': ${e}`),a=void 0,i.push(new en(`${n.transport} failed: ${e}`,bn[n.transport])),"Connecting"!==this._connectionState){const e="Failed to select transport before stop() was called.";return this._logger.log(Mt.Debug,e),Promise.reject(new Yt(e))}}}}return i.length>0?Promise.reject(new nn(`Unable to connect to the server with any of the available transports. ${i.join(" ")}`,i)):Promise.reject(new Error("None of the transports supported by the client are supported by the server."))}_constructTransport(e){switch(e){case bn.WebSockets:if(!this._options.WebSocket)throw new Error("'WebSocket' is not supported in your environment.");return new In(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent,this._options.WebSocket,this._options.headers||{});case bn.ServerSentEvents:if(!this._options.EventSource)throw new Error("'EventSource' is not supported in your environment.");return new Cn(this._httpClient,this._httpClient._accessToken,this._logger,this._options);case bn.LongPolling:return new Sn(this._httpClient,this._logger,this._options);default:throw new Error(`Unknown transport: ${e}.`)}}_startTransport(e,t){return this.transport.onreceive=this.onreceive,this.features.reconnect?this.transport.onclose=async n=>{let o=!1;if(this.features.reconnect){try{this.features.disconnected(),await this.transport.connect(e,t),await this.features.resend()}catch{o=!0}o&&this._stopConnection(n)}else this._stopConnection(n)}:this.transport.onclose=e=>this._stopConnection(e),this.transport.connect(e,t)}_resolveTransportOrError(e,t,n,o){const r=bn[e.transport];if(null==r)return this._logger.log(Mt.Debug,`Skipping transport '${e.transport}' because it is not supported by this client.`),new Error(`Skipping transport '${e.transport}' because it is not supported by this client.`);if(!function(e,t){return!e||0!=(t&e)}(t,r))return this._logger.log(Mt.Debug,`Skipping transport '${bn[r]}' because it was disabled by the client.`),new Zt(`'${bn[r]}' is disabled by the client.`,r);if(!(e.transferFormats.map((e=>_n[e])).indexOf(n)>=0))return this._logger.log(Mt.Debug,`Skipping transport '${bn[r]}' because it does not support the requested transfer format '${_n[n]}'.`),new Error(`'${bn[r]}' does not support ${_n[n]}.`);if(r===bn.WebSockets&&!this._options.WebSocket||r===bn.ServerSentEvents&&!this._options.EventSource)return this._logger.log(Mt.Debug,`Skipping transport '${bn[r]}' because it is not supported in your environment.'`),new Qt(`'${bn[r]}' is not supported in your environment.`,r);this._logger.log(Mt.Debug,`Selecting transport '${bn[r]}'.`);try{return this.features.reconnect=r===bn.WebSockets?o:void 0,this._constructTransport(r)}catch(e){return e}}_isITransport(e){return e&&"object"==typeof e&&"connect"in e}_stopConnection(e){if(this._logger.log(Mt.Debug,`HttpConnection.stopConnection(${e}) called while in state ${this._connectionState}.`),this.transport=void 0,e=this._stopError||e,this._stopError=void 0,"Disconnected"!==this._connectionState){if("Connecting"===this._connectionState)throw this._logger.log(Mt.Warning,`Call to HttpConnection.stopConnection(${e}) was ignored because the connection is still in the connecting state.`),new Error(`HttpConnection.stopConnection(${e}) was called while the connection is still in the connecting state.`);if("Disconnecting"===this._connectionState&&this._stopPromiseResolver(),e?this._logger.log(Mt.Error,`Connection disconnected with error '${e}'.`):this._logger.log(Mt.Information,"Connection disconnected."),this._sendQueue&&(this._sendQueue.stop().catch((e=>{this._logger.log(Mt.Error,`TransportSendQueue.stop() threw error '${e}'.`)})),this._sendQueue=void 0),this.connectionId=void 0,this._connectionState="Disconnected",this._connectionStarted){this._connectionStarted=!1;try{this.onclose&&this.onclose(e)}catch(t){this._logger.log(Mt.Error,`HttpConnection.onclose(${e}) threw error '${t}'.`)}}}else this._logger.log(Mt.Debug,`Call to HttpConnection.stopConnection(${e}) was ignored because the connection is already in the disconnected state.`)}_resolveUrl(e){if(0===e.lastIndexOf("https://",0)||0===e.lastIndexOf("http://",0))return e;if(!Bt.isBrowser)throw new Error(`Cannot resolve '${e}'.`);const t=window.document.createElement("a");return t.href=e,this._logger.log(Mt.Information,`Normalizing '${e}' to '${t.href}'.`),t.href}_resolveNegotiateUrl(e){const t=new URL(e);t.pathname.endsWith("/")?t.pathname+="negotiate":t.pathname+="/negotiate";const n=new URLSearchParams(t.searchParams);return n.has("negotiateVersion")||n.append("negotiateVersion",this._negotiateVersion.toString()),n.has("useStatefulReconnect")?"true"===n.get("useStatefulReconnect")&&(this._options._useStatefulReconnect=!0):!0===this._options._useStatefulReconnect&&n.append("useStatefulReconnect","true"),t.search=n.toString(),t.toString()}}class Tn{constructor(e){this._transport=e,this._buffer=[],this._executing=!0,this._sendBufferedData=new Dn,this._transportResult=new Dn,this._sendLoopPromise=this._sendLoop()}send(e){return this._bufferData(e),this._transportResult||(this._transportResult=new Dn),this._transportResult.promise}stop(){return this._executing=!1,this._sendBufferedData.resolve(),this._sendLoopPromise}_bufferData(e){if(this._buffer.length&&typeof this._buffer[0]!=typeof e)throw new Error(`Expected data to be of type ${typeof this._buffer} but was of type ${typeof e}`);this._buffer.push(e),this._sendBufferedData.resolve()}async _sendLoop(){for(;;){if(await this._sendBufferedData.promise,!this._executing){this._transportResult&&this._transportResult.reject("Connection stopped.");break}this._sendBufferedData=new Dn;const e=this._transportResult;this._transportResult=void 0;const t="string"==typeof this._buffer[0]?this._buffer.join(""):Tn._concatBuffers(this._buffer);this._buffer.length=0;try{await this._transport.send(t),e.resolve()}catch(t){e.reject(t)}}}static _concatBuffers(e){const t=e.map((e=>e.byteLength)).reduce(((e,t)=>e+t)),n=new Uint8Array(t);let o=0;for(const t of e)n.set(new Uint8Array(t),o),o+=t.byteLength;return n.buffer}}class Dn{constructor(){this.promise=new Promise(((e,t)=>[this._resolver,this._rejecter]=[e,t]))}resolve(){this._resolver()}reject(e){this._rejecter(e)}}class Rn{constructor(){this.name="json",this.version=2,this.transferFormat=_n.Text}parseMessages(e,t){if("string"!=typeof e)throw new Error("Invalid input for JSON hub protocol. Expected a string.");if(!e)return[];null===t&&(t=Pt.instance);const n=Nt.parse(e),o=[];for(const e of n){const n=JSON.parse(e);if("number"!=typeof n.type)throw new Error("Invalid payload.");switch(n.type){case on.Invocation:this._isInvocationMessage(n);break;case on.StreamItem:this._isStreamItemMessage(n);break;case on.Completion:this._isCompletionMessage(n);break;case on.Ping:case on.Close:break;case on.Ack:this._isAckMessage(n);break;case on.Sequence:this._isSequenceMessage(n);break;default:t.log(Mt.Information,"Unknown message type '"+n.type+"' ignored.");continue}o.push(n)}return o}writeMessage(e){return Nt.write(JSON.stringify(e))}_isInvocationMessage(e){this._assertNotEmptyString(e.target,"Invalid payload for Invocation message."),void 0!==e.invocationId&&this._assertNotEmptyString(e.invocationId,"Invalid payload for Invocation message.")}_isStreamItemMessage(e){if(this._assertNotEmptyString(e.invocationId,"Invalid payload for StreamItem message."),void 0===e.item)throw new Error("Invalid payload for StreamItem message.")}_isCompletionMessage(e){if(e.result&&e.error)throw new Error("Invalid payload for Completion message.");!e.result&&e.error&&this._assertNotEmptyString(e.error,"Invalid payload for Completion message."),this._assertNotEmptyString(e.invocationId,"Invalid payload for Completion message.")}_isAckMessage(e){if("number"!=typeof e.sequenceId)throw new Error("Invalid SequenceId for Ack message.")}_isSequenceMessage(e){if("number"!=typeof e.sequenceId)throw new Error("Invalid SequenceId for Sequence message.")}_assertNotEmptyString(e,t){if("string"!=typeof e||""===e)throw new Error(t)}}const An={trace:Mt.Trace,debug:Mt.Debug,info:Mt.Information,information:Mt.Information,warn:Mt.Warning,warning:Mt.Warning,error:Mt.Error,critical:Mt.Critical,none:Mt.None};class xn{configureLogging(e){if(Lt.isRequired(e,"logging"),function(e){return void 0!==e.log}(e))this.logger=e;else if("string"==typeof e){const t=function(e){const t=An[e.toLowerCase()];if(void 0!==t)return t;throw new Error(`Unknown log level: ${e}`)}(e);this.logger=new jt(t)}else this.logger=new jt(e);return this}withUrl(e,t){return Lt.isRequired(e,"url"),Lt.isNotEmpty(e,"url"),this.url=e,this.httpConnectionOptions="object"==typeof t?{...this.httpConnectionOptions,...t}:{...this.httpConnectionOptions,transport:t},this}withHubProtocol(e){return Lt.isRequired(e,"protocol"),this.protocol=e,this}withAutomaticReconnect(e){if(this.reconnectPolicy)throw new Error("A reconnectPolicy has already been set.");return e?Array.isArray(e)?this.reconnectPolicy=new dn(e):this.reconnectPolicy=e:this.reconnectPolicy=new dn,this}withServerTimeout(e){return Lt.isRequired(e,"milliseconds"),this._serverTimeoutInMilliseconds=e,this}withKeepAliveInterval(e){return Lt.isRequired(e,"milliseconds"),this._keepAliveIntervalInMilliseconds=e,this}withStatefulReconnect(e){return void 0===this.httpConnectionOptions&&(this.httpConnectionOptions={}),this.httpConnectionOptions._useStatefulReconnect=!0,this._statefulReconnectBufferSize=null==e?void 0:e.bufferSize,this}build(){const e=this.httpConnectionOptions||{};if(void 0===e.logger&&(e.logger=this.logger),!this.url)throw new Error("The 'HubConnectionBuilder.withUrl' method must be called before building the connection.");const t=new kn(this.url,e);return ln.create(t,this.logger||Pt.instance,this.protocol||new Rn,this.reconnectPolicy,this._serverTimeoutInMilliseconds,this._keepAliveIntervalInMilliseconds,this._statefulReconnectBufferSize)}}var Nn;!function(e){e[e.Default=0]="Default",e[e.Server=1]="Server",e[e.WebAssembly=2]="WebAssembly",e[e.WebView=3]="WebView"}(Nn||(Nn={}));var Mn,Pn,Un,Ln=4294967295;function Bn(e,t,n){var o=Math.floor(n/4294967296),r=n;e.setUint32(t,o),e.setUint32(t+4,r)}function Fn(e,t){return 4294967296*e.getInt32(t)+e.getUint32(t+4)}var On=("undefined"==typeof process||"never"!==(null===(Mn=null===process||void 0===process?void 0:process.env)||void 0===Mn?void 0:Mn.TEXT_ENCODING))&&"undefined"!=typeof TextEncoder&&"undefined"!=typeof TextDecoder;function $n(e){for(var t=e.length,n=0,o=0;o=55296&&r<=56319&&o65535&&(h-=65536,i.push(h>>>10&1023|55296),h=56320|1023&h),i.push(h)}else i.push(a);i.length>=4096&&(s+=String.fromCharCode.apply(String,i),i.length=0)}return i.length>0&&(s+=String.fromCharCode.apply(String,i)),s}var zn,Jn=On?new TextDecoder:null,Vn=On?"undefined"!=typeof process&&"force"!==(null===(Un=null===process||void 0===process?void 0:process.env)||void 0===Un?void 0:Un.TEXT_DECODER)?200:0:Ln,Kn=function(e,t){this.type=e,this.data=t},Xn=(zn=function(e,t){return zn=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},zn(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function n(){this.constructor=e}zn(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}),Gn=function(e){function t(n){var o=e.call(this,n)||this,r=Object.create(t.prototype);return Object.setPrototypeOf(o,r),Object.defineProperty(o,"name",{configurable:!0,enumerable:!1,value:t.name}),o}return Xn(t,e),t}(Error),Yn={type:-1,encode:function(e){var t,n,o,r;return e instanceof Date?function(e){var t,n=e.sec,o=e.nsec;if(n>=0&&o>=0&&n<=17179869183){if(0===o&&n<=4294967295){var r=new Uint8Array(4);return(t=new DataView(r.buffer)).setUint32(0,n),r}var i=n/4294967296,s=4294967295&n;return r=new Uint8Array(8),(t=new DataView(r.buffer)).setUint32(0,o<<2|3&i),t.setUint32(4,s),r}return r=new Uint8Array(12),(t=new DataView(r.buffer)).setUint32(0,o),Bn(t,4,n),r}((o=1e6*((t=e.getTime())-1e3*(n=Math.floor(t/1e3))),{sec:n+(r=Math.floor(o/1e9)),nsec:o-1e9*r})):null},decode:function(e){var t=function(e){var t=new DataView(e.buffer,e.byteOffset,e.byteLength);switch(e.byteLength){case 4:return{sec:t.getUint32(0),nsec:0};case 8:var n=t.getUint32(0);return{sec:4294967296*(3&n)+t.getUint32(4),nsec:n>>>2};case 12:return{sec:Fn(t,4),nsec:t.getUint32(0)};default:throw new Gn("Unrecognized data size for timestamp (expected 4, 8, or 12): ".concat(e.length))}}(e);return new Date(1e3*t.sec+t.nsec/1e6)}},Qn=function(){function e(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(Yn)}return e.prototype.register=function(e){var t=e.type,n=e.encode,o=e.decode;if(t>=0)this.encoders[t]=n,this.decoders[t]=o;else{var r=1+t;this.builtInEncoders[r]=n,this.builtInDecoders[r]=o}},e.prototype.tryToEncode=function(e,t){for(var n=0;nthis.maxDepth)throw new Error("Too deep objects in depth ".concat(t));null==e?this.encodeNil():"boolean"==typeof e?this.encodeBoolean(e):"number"==typeof e?this.encodeNumber(e):"string"==typeof e?this.encodeString(e):this.encodeObject(e,t)},e.prototype.ensureBufferSizeToWrite=function(e){var t=this.pos+e;this.view.byteLength=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):(this.writeU8(211),this.writeI64(e)):this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))},e.prototype.writeStringHeader=function(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else{if(!(e<4294967296))throw new Error("Too long string: ".concat(e," bytes in UTF-8"));this.writeU8(219),this.writeU32(e)}},e.prototype.encodeString=function(e){if(e.length>jn){var t=$n(e);this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),Wn(e,this.bytes,this.pos),this.pos+=t}else t=$n(e),this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),function(e,t,n){for(var o=e.length,r=n,i=0;i>6&31|192;else{if(s>=55296&&s<=56319&&i>12&15|224,t[r++]=s>>6&63|128):(t[r++]=s>>18&7|240,t[r++]=s>>12&63|128,t[r++]=s>>6&63|128)}t[r++]=63&s|128}else t[r++]=s}}(e,this.bytes,this.pos),this.pos+=t},e.prototype.encodeObject=function(e,t){var n=this.extensionCodec.tryToEncode(e,this.context);if(null!=n)this.encodeExtension(n);else if(Array.isArray(e))this.encodeArray(e,t);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else{if("object"!=typeof e)throw new Error("Unrecognized object: ".concat(Object.prototype.toString.apply(e)));this.encodeMap(e,t)}},e.prototype.encodeBinary=function(e){var t=e.byteLength;if(t<256)this.writeU8(196),this.writeU8(t);else if(t<65536)this.writeU8(197),this.writeU16(t);else{if(!(t<4294967296))throw new Error("Too large binary: ".concat(t));this.writeU8(198),this.writeU32(t)}var n=Zn(e);this.writeU8a(n)},e.prototype.encodeArray=function(e,t){var n=e.length;if(n<16)this.writeU8(144+n);else if(n<65536)this.writeU8(220),this.writeU16(n);else{if(!(n<4294967296))throw new Error("Too large array: ".concat(n));this.writeU8(221),this.writeU32(n)}for(var o=0,r=e;o0&&e<=this.maxKeyLength},e.prototype.find=function(e,t,n){e:for(var o=0,r=this.caches[n-1];o=this.maxLengthPerKey?n[Math.random()*n.length|0]=o:n.push(o)},e.prototype.decode=function(e,t,n){var o=this.find(e,t,n);if(null!=o)return this.hit++,o;this.miss++;var r=qn(e,t,n),i=Uint8Array.prototype.slice.call(e,t,t+n);return this.store(i,r),r},e}(),oo=function(e,t){var n,o,r,i,s={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return i={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(i){return function(a){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,o&&(r=2&i[0]?o.return:i[0]?o.throw||((r=o.return)&&r.call(o),0):o.next)&&!(r=r.call(o,i[1])).done)return r;switch(o=0,r&&(i=[2&i[0],r.value]),i[0]){case 0:case 1:r=i;break;case 4:return s.label++,{value:i[1],done:!1};case 5:s.label++,o=i[1],i=[0];continue;case 7:i=s.ops.pop(),s.trys.pop();continue;default:if(!((r=(r=s.trys).length>0&&r[r.length-1])||6!==i[0]&&2!==i[0])){s=0;continue}if(3===i[0]&&(!r||i[1]>r[0]&&i[1]=e},e.prototype.createExtraByteError=function(e){var t=this.view,n=this.pos;return new RangeError("Extra ".concat(t.byteLength-n," of ").concat(t.byteLength," byte(s) found at buffer[").concat(e,"]"))},e.prototype.decode=function(e){this.reinitializeState(),this.setBuffer(e);var t=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return t},e.prototype.decodeMulti=function(e){return oo(this,(function(t){switch(t.label){case 0:this.reinitializeState(),this.setBuffer(e),t.label=1;case 1:return this.hasRemaining(1)?[4,this.doDecodeSync()]:[3,3];case 2:return t.sent(),[3,1];case 3:return[2]}}))},e.prototype.decodeAsync=function(e){var t,n,o,r,i,s,a;return i=this,void 0,a=function(){var i,s,a,c,l,h,d,u;return oo(this,(function(p){switch(p.label){case 0:i=!1,p.label=1;case 1:p.trys.push([1,6,7,12]),t=ro(e),p.label=2;case 2:return[4,t.next()];case 3:if((n=p.sent()).done)return[3,5];if(a=n.value,i)throw this.createExtraByteError(this.totalPos);this.appendBuffer(a);try{s=this.doDecodeSync(),i=!0}catch(e){if(!(e instanceof co))throw e}this.totalPos+=this.pos,p.label=4;case 4:return[3,2];case 5:return[3,12];case 6:return c=p.sent(),o={error:c},[3,12];case 7:return p.trys.push([7,,10,11]),n&&!n.done&&(r=t.return)?[4,r.call(t)]:[3,9];case 8:p.sent(),p.label=9;case 9:return[3,11];case 10:if(o)throw o.error;return[7];case 11:return[7];case 12:if(i){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return[2,s]}throw h=(l=this).headByte,d=l.pos,u=l.totalPos,new RangeError("Insufficient data in parsing ".concat(to(h)," at ").concat(u," (").concat(d," in the current buffer)"))}}))},new((s=void 0)||(s=Promise))((function(e,t){function n(e){try{r(a.next(e))}catch(e){t(e)}}function o(e){try{r(a.throw(e))}catch(e){t(e)}}function r(t){var r;t.done?e(t.value):(r=t.value,r instanceof s?r:new s((function(e){e(r)}))).then(n,o)}r((a=a.apply(i,[])).next())}))},e.prototype.decodeArrayStream=function(e){return this.decodeMultiAsync(e,!0)},e.prototype.decodeStream=function(e){return this.decodeMultiAsync(e,!1)},e.prototype.decodeMultiAsync=function(e,t){return function(n,o,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i,s=function(){var n,o,r,i,s,a,c,l,h;return oo(this,(function(d){switch(d.label){case 0:n=t,o=-1,d.label=1;case 1:d.trys.push([1,13,14,19]),r=ro(e),d.label=2;case 2:return[4,io(r.next())];case 3:if((i=d.sent()).done)return[3,12];if(s=i.value,t&&0===o)throw this.createExtraByteError(this.totalPos);this.appendBuffer(s),n&&(o=this.readArraySize(),n=!1,this.complete()),d.label=4;case 4:d.trys.push([4,9,,10]),d.label=5;case 5:return[4,io(this.doDecodeSync())];case 6:return[4,d.sent()];case 7:return d.sent(),0==--o?[3,8]:[3,5];case 8:return[3,10];case 9:if(!((a=d.sent())instanceof co))throw a;return[3,10];case 10:this.totalPos+=this.pos,d.label=11;case 11:return[3,2];case 12:return[3,19];case 13:return c=d.sent(),l={error:c},[3,19];case 14:return d.trys.push([14,,17,18]),i&&!i.done&&(h=r.return)?[4,io(h.call(r))]:[3,16];case 15:d.sent(),d.label=16;case 16:return[3,18];case 17:if(l)throw l.error;return[7];case 18:return[7];case 19:return[2]}}))}.apply(n,o||[]),a=[];return i={},c("next"),c("throw"),c("return"),i[Symbol.asyncIterator]=function(){return this},i;function c(e){s[e]&&(i[e]=function(t){return new Promise((function(n,o){a.push([e,t,n,o])>1||l(e,t)}))})}function l(e,t){try{(n=s[e](t)).value instanceof io?Promise.resolve(n.value.v).then(h,d):u(a[0][2],n)}catch(e){u(a[0][3],e)}var n}function h(e){l("next",e)}function d(e){l("throw",e)}function u(e,t){e(t),a.shift(),a.length&&l(a[0][0],a[0][1])}}(this,arguments)},e.prototype.doDecodeSync=function(){e:for(;;){var e=this.readHeadByte(),t=void 0;if(e>=224)t=e-256;else if(e<192)if(e<128)t=e;else if(e<144){if(0!=(o=e-128)){this.pushMapState(o),this.complete();continue e}t={}}else if(e<160){if(0!=(o=e-144)){this.pushArrayState(o),this.complete();continue e}t=[]}else{var n=e-160;t=this.decodeUtf8String(n,0)}else if(192===e)t=null;else if(194===e)t=!1;else if(195===e)t=!0;else if(202===e)t=this.readF32();else if(203===e)t=this.readF64();else if(204===e)t=this.readU8();else if(205===e)t=this.readU16();else if(206===e)t=this.readU32();else if(207===e)t=this.readU64();else if(208===e)t=this.readI8();else if(209===e)t=this.readI16();else if(210===e)t=this.readI32();else if(211===e)t=this.readI64();else if(217===e)n=this.lookU8(),t=this.decodeUtf8String(n,1);else if(218===e)n=this.lookU16(),t=this.decodeUtf8String(n,2);else if(219===e)n=this.lookU32(),t=this.decodeUtf8String(n,4);else if(220===e){if(0!==(o=this.readU16())){this.pushArrayState(o),this.complete();continue e}t=[]}else if(221===e){if(0!==(o=this.readU32())){this.pushArrayState(o),this.complete();continue e}t=[]}else if(222===e){if(0!==(o=this.readU16())){this.pushMapState(o),this.complete();continue e}t={}}else if(223===e){if(0!==(o=this.readU32())){this.pushMapState(o),this.complete();continue e}t={}}else if(196===e){var o=this.lookU8();t=this.decodeBinary(o,1)}else if(197===e)o=this.lookU16(),t=this.decodeBinary(o,2);else if(198===e)o=this.lookU32(),t=this.decodeBinary(o,4);else if(212===e)t=this.decodeExtension(1,0);else if(213===e)t=this.decodeExtension(2,0);else if(214===e)t=this.decodeExtension(4,0);else if(215===e)t=this.decodeExtension(8,0);else if(216===e)t=this.decodeExtension(16,0);else if(199===e)o=this.lookU8(),t=this.decodeExtension(o,1);else if(200===e)o=this.lookU16(),t=this.decodeExtension(o,2);else{if(201!==e)throw new Gn("Unrecognized type byte: ".concat(to(e)));o=this.lookU32(),t=this.decodeExtension(o,4)}this.complete();for(var r=this.stack;r.length>0;){var i=r[r.length-1];if(0===i.type){if(i.array[i.position]=t,i.position++,i.position!==i.size)continue e;r.pop(),t=i.array}else{if(1===i.type){if("string"!=(s=typeof t)&&"number"!==s)throw new Gn("The type of key must be string or number but "+typeof t);if("__proto__"===t)throw new Gn("The key __proto__ is not allowed");i.key=t,i.type=2;continue e}if(i.map[i.key]=t,i.readCount++,i.readCount!==i.size){i.key=null,i.type=1;continue e}r.pop(),t=i.map}}return t}var s},e.prototype.readHeadByte=function(){return-1===this.headByte&&(this.headByte=this.readU8()),this.headByte},e.prototype.complete=function(){this.headByte=-1},e.prototype.readArraySize=function(){var e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:if(e<160)return e-144;throw new Gn("Unrecognized array type byte: ".concat(to(e)))}},e.prototype.pushMapState=function(e){if(e>this.maxMapLength)throw new Gn("Max length exceeded: map length (".concat(e,") > maxMapLengthLength (").concat(this.maxMapLength,")"));this.stack.push({type:1,size:e,key:null,readCount:0,map:{}})},e.prototype.pushArrayState=function(e){if(e>this.maxArrayLength)throw new Gn("Max length exceeded: array length (".concat(e,") > maxArrayLength (").concat(this.maxArrayLength,")"));this.stack.push({type:0,size:e,array:new Array(e),position:0})},e.prototype.decodeUtf8String=function(e,t){var n;if(e>this.maxStrLength)throw new Gn("Max length exceeded: UTF-8 byte length (".concat(e,") > maxStrLength (").concat(this.maxStrLength,")"));if(this.bytes.byteLengthVn?function(e,t,n){var o=e.subarray(t,t+n);return Jn.decode(o)}(this.bytes,r,e):qn(this.bytes,r,e),this.pos+=t+e,o},e.prototype.stateIsMapKey=function(){return this.stack.length>0&&1===this.stack[this.stack.length-1].type},e.prototype.decodeBinary=function(e,t){if(e>this.maxBinLength)throw new Gn("Max length exceeded: bin length (".concat(e,") > maxBinLength (").concat(this.maxBinLength,")"));if(!this.hasRemaining(e+t))throw lo;var n=this.pos+t,o=this.bytes.subarray(n,n+e);return this.pos+=t+e,o},e.prototype.decodeExtension=function(e,t){if(e>this.maxExtLength)throw new Gn("Max length exceeded: ext length (".concat(e,") > maxExtLength (").concat(this.maxExtLength,")"));var n=this.view.getInt8(this.pos+t),o=this.decodeBinary(e,t+1);return this.extensionCodec.decode(o,n,this.context)},e.prototype.lookU8=function(){return this.view.getUint8(this.pos)},e.prototype.lookU16=function(){return this.view.getUint16(this.pos)},e.prototype.lookU32=function(){return this.view.getUint32(this.pos)},e.prototype.readU8=function(){var e=this.view.getUint8(this.pos);return this.pos++,e},e.prototype.readI8=function(){var e=this.view.getInt8(this.pos);return this.pos++,e},e.prototype.readU16=function(){var e=this.view.getUint16(this.pos);return this.pos+=2,e},e.prototype.readI16=function(){var e=this.view.getInt16(this.pos);return this.pos+=2,e},e.prototype.readU32=function(){var e=this.view.getUint32(this.pos);return this.pos+=4,e},e.prototype.readI32=function(){var e=this.view.getInt32(this.pos);return this.pos+=4,e},e.prototype.readU64=function(){var e,t,n=(e=this.view,t=this.pos,4294967296*e.getUint32(t)+e.getUint32(t+4));return this.pos+=8,n},e.prototype.readI64=function(){var e=Fn(this.view,this.pos);return this.pos+=8,e},e.prototype.readF32=function(){var e=this.view.getFloat32(this.pos);return this.pos+=4,e},e.prototype.readF64=function(){var e=this.view.getFloat64(this.pos);return this.pos+=8,e},e}();class po{static write(e){let t=e.byteLength||e.length;const n=[];do{let e=127&t;t>>=7,t>0&&(e|=128),n.push(e)}while(t>0);t=e.byteLength||e.length;const o=new Uint8Array(n.length+t);return o.set(n,0),o.set(e,n.length),o.buffer}static parse(e){const t=[],n=new Uint8Array(e),o=[0,7,14,21,28];for(let r=0;r7)throw new Error("Messages bigger than 2GB are not supported.");if(!(n.byteLength>=r+s+a))throw new Error("Incomplete message.");t.push(n.slice?n.slice(r+s,r+s+a):n.subarray(r+s,r+s+a)),r=r+s+a}return t}}const fo=new Uint8Array([145,on.Ping]);class go{constructor(e){this.name="messagepack",this.version=2,this.transferFormat=_n.Binary,this._errorResult=1,this._voidResult=2,this._nonVoidResult=3,e=e||{},this._encoder=new eo(e.extensionCodec,e.context,e.maxDepth,e.initialBufferSize,e.sortKeys,e.forceFloat32,e.ignoreUndefined,e.forceIntegerToFloat),this._decoder=new uo(e.extensionCodec,e.context,e.maxStrLength,e.maxBinLength,e.maxArrayLength,e.maxMapLength,e.maxExtLength)}parseMessages(e,t){if(!(n=e)||"undefined"==typeof ArrayBuffer||!(n instanceof ArrayBuffer||n.constructor&&"ArrayBuffer"===n.constructor.name))throw new Error("Invalid input for MessagePack hub protocol. Expected an ArrayBuffer.");var n;null===t&&(t=Pt.instance);const o=po.parse(e),r=[];for(const e of o){const n=this._parseMessage(e,t);n&&r.push(n)}return r}writeMessage(e){switch(e.type){case on.Invocation:return this._writeInvocation(e);case on.StreamInvocation:return this._writeStreamInvocation(e);case on.StreamItem:return this._writeStreamItem(e);case on.Completion:return this._writeCompletion(e);case on.Ping:return po.write(fo);case on.CancelInvocation:return this._writeCancelInvocation(e);case on.Close:return this._writeClose();case on.Ack:return this._writeAck(e);case on.Sequence:return this._writeSequence(e);default:throw new Error("Invalid message type.")}}_parseMessage(e,t){if(0===e.length)throw new Error("Invalid payload.");const n=this._decoder.decode(e);if(0===n.length||!(n instanceof Array))throw new Error("Invalid payload.");const o=n[0];switch(o){case on.Invocation:return this._createInvocationMessage(this._readHeaders(n),n);case on.StreamItem:return this._createStreamItemMessage(this._readHeaders(n),n);case on.Completion:return this._createCompletionMessage(this._readHeaders(n),n);case on.Ping:return this._createPingMessage(n);case on.Close:return this._createCloseMessage(n);case on.Ack:return this._createAckMessage(n);case on.Sequence:return this._createSequenceMessage(n);default:return t.log(Mt.Information,"Unknown message type '"+o+"' ignored."),null}}_createCloseMessage(e){if(e.length<2)throw new Error("Invalid payload for Close message.");return{allowReconnect:e.length>=3?e[2]:void 0,error:e[1],type:on.Close}}_createPingMessage(e){if(e.length<1)throw new Error("Invalid payload for Ping message.");return{type:on.Ping}}_createInvocationMessage(e,t){if(t.length<5)throw new Error("Invalid payload for Invocation message.");const n=t[2];return n?{arguments:t[4],headers:e,invocationId:n,streamIds:[],target:t[3],type:on.Invocation}:{arguments:t[4],headers:e,streamIds:[],target:t[3],type:on.Invocation}}_createStreamItemMessage(e,t){if(t.length<4)throw new Error("Invalid payload for StreamItem message.");return{headers:e,invocationId:t[2],item:t[3],type:on.StreamItem}}_createCompletionMessage(e,t){if(t.length<4)throw new Error("Invalid payload for Completion message.");const n=t[3];if(n!==this._voidResult&&t.length<5)throw new Error("Invalid payload for Completion message.");let o,r;switch(n){case this._errorResult:o=t[4];break;case this._nonVoidResult:r=t[4]}return{error:o,headers:e,invocationId:t[2],result:r,type:on.Completion}}_createAckMessage(e){if(e.length<1)throw new Error("Invalid payload for Ack message.");return{sequenceId:e[1],type:on.Ack}}_createSequenceMessage(e){if(e.length<1)throw new Error("Invalid payload for Sequence message.");return{sequenceId:e[1],type:on.Sequence}}_writeInvocation(e){let t;return t=e.streamIds?this._encoder.encode([on.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments,e.streamIds]):this._encoder.encode([on.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments]),po.write(t.slice())}_writeStreamInvocation(e){let t;return t=e.streamIds?this._encoder.encode([on.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments,e.streamIds]):this._encoder.encode([on.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments]),po.write(t.slice())}_writeStreamItem(e){const t=this._encoder.encode([on.StreamItem,e.headers||{},e.invocationId,e.item]);return po.write(t.slice())}_writeCompletion(e){const t=e.error?this._errorResult:void 0!==e.result?this._nonVoidResult:this._voidResult;let n;switch(t){case this._errorResult:n=this._encoder.encode([on.Completion,e.headers||{},e.invocationId,t,e.error]);break;case this._voidResult:n=this._encoder.encode([on.Completion,e.headers||{},e.invocationId,t]);break;case this._nonVoidResult:n=this._encoder.encode([on.Completion,e.headers||{},e.invocationId,t,e.result])}return po.write(n.slice())}_writeCancelInvocation(e){const t=this._encoder.encode([on.CancelInvocation,e.headers||{},e.invocationId]);return po.write(t.slice())}_writeClose(){const e=this._encoder.encode([on.Close,null]);return po.write(e.slice())}_writeAck(e){const t=this._encoder.encode([on.Ack,e.sequenceId]);return po.write(t.slice())}_writeSequence(e){const t=this._encoder.encode([on.Sequence,e.sequenceId]);return po.write(t.slice())}_readHeaders(e){const t=e[1];if("object"!=typeof t)throw new Error("Invalid headers.");return t}}const mo="function"==typeof TextDecoder?new TextDecoder("utf-8"):null,vo=mo?mo.decode.bind(mo):function(e){let t=0;const n=e.length,o=[],r=[];for(;t65535&&(r-=65536,o.push(r>>>10&1023|55296),r=56320|1023&r),o.push(r)}o.length>1024&&(r.push(String.fromCharCode.apply(null,o)),o.length=0)}return r.push(String.fromCharCode.apply(null,o)),r.join("")},yo=Math.pow(2,32),wo=Math.pow(2,21)-1;function bo(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}function _o(e,t){return e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24>>>0)}function Eo(e,t){const n=_o(e,t+4);if(n>wo)throw new Error(`Cannot read uint64 with high order part ${n}, because the result would exceed Number.MAX_SAFE_INTEGER.`);return n*yo+_o(e,t)}class So{constructor(e){this.batchData=e;const t=new To(e);this.arrayRangeReader=new Do(e),this.arrayBuilderSegmentReader=new Ro(e),this.diffReader=new Co(e),this.editReader=new Io(e,t),this.frameReader=new ko(e,t)}updatedComponents(){return bo(this.batchData,this.batchData.length-20)}referenceFrames(){return bo(this.batchData,this.batchData.length-16)}disposedComponentIds(){return bo(this.batchData,this.batchData.length-12)}disposedEventHandlerIds(){return bo(this.batchData,this.batchData.length-8)}updatedComponentsEntry(e,t){const n=e+4*t;return bo(this.batchData,n)}referenceFramesEntry(e,t){return e+20*t}disposedComponentIdsEntry(e,t){const n=e+4*t;return bo(this.batchData,n)}disposedEventHandlerIdsEntry(e,t){const n=e+8*t;return Eo(this.batchData,n)}}class Co{constructor(e){this.batchDataUint8=e}componentId(e){return bo(this.batchDataUint8,e)}edits(e){return e+4}editsEntry(e,t){return e+16*t}}class Io{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}editType(e){return bo(this.batchDataUint8,e)}siblingIndex(e){return bo(this.batchDataUint8,e+4)}newTreeIndex(e){return bo(this.batchDataUint8,e+8)}moveToSiblingIndex(e){return bo(this.batchDataUint8,e+8)}removedAttributeName(e){const t=bo(this.batchDataUint8,e+12);return this.stringReader.readString(t)}}class ko{constructor(e,t){this.batchDataUint8=e,this.stringReader=t}frameType(e){return bo(this.batchDataUint8,e)}subtreeLength(e){return bo(this.batchDataUint8,e+4)}elementReferenceCaptureId(e){const t=bo(this.batchDataUint8,e+4);return this.stringReader.readString(t)}componentId(e){return bo(this.batchDataUint8,e+8)}elementName(e){const t=bo(this.batchDataUint8,e+8);return this.stringReader.readString(t)}textContent(e){const t=bo(this.batchDataUint8,e+4);return this.stringReader.readString(t)}markupContent(e){const t=bo(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeName(e){const t=bo(this.batchDataUint8,e+4);return this.stringReader.readString(t)}attributeValue(e){const t=bo(this.batchDataUint8,e+8);return this.stringReader.readString(t)}attributeEventHandlerId(e){return Eo(this.batchDataUint8,e+12)}}class To{constructor(e){this.batchDataUint8=e,this.stringTableStartIndex=bo(e,e.length-4)}readString(e){if(-1===e)return null;{const n=bo(this.batchDataUint8,this.stringTableStartIndex+4*e),o=function(e,t){let n=0,o=0;for(let r=0;r<4;r++){const i=e[t+r];if(n|=(127&i)<this.nextBatchId)return this.fatalError?(this.logger.log(ft.Debug,`Received a new batch ${e} but errored out on a previous batch ${this.nextBatchId-1}`),void await n.send("OnRenderCompleted",this.nextBatchId-1,this.fatalError.toString())):void this.logger.log(ft.Debug,`Waiting for batch ${this.nextBatchId}. Batch ${e} not processed.`);try{this.nextBatchId++,this.logger.log(ft.Debug,`Applying batch ${e}.`),Ce(Nn.Server,new So(t)),await this.completeBatch(n,e)}catch(t){throw this.fatalError=t.toString(),this.logger.log(ft.Error,`There was an error applying batch ${e}.`),n.send("OnRenderCompleted",e,t.toString()),t}}getLastBatchid(){return this.nextBatchId-1}async completeBatch(e,t){try{await e.send("OnRenderCompleted",t,null)}catch{this.logger.log(ft.Warning,`Failed to deliver completion notification for render '${t}'.`)}}}let xo=!1;function No(){const e=document.querySelector("#blazor-error-ui");e&&(e.style.display="block"),xo||(xo=!0,document.querySelectorAll("#blazor-error-ui .reload").forEach((e=>{e.onclick=function(e){location.reload(),e.preventDefault()}})),document.querySelectorAll("#blazor-error-ui .dismiss").forEach((e=>{e.onclick=function(e){const t=document.querySelector("#blazor-error-ui");t&&(t.style.display="none"),e.preventDefault()}})))}class Mo{constructor(t,n,o,r){this._firstUpdate=!0,this._renderingFailed=!1,this._disposed=!1,this._circuitId=void 0,this._applicationState=n,this._componentManager=t,this._options=o,this._logger=r,this._renderQueue=new Ao(this._logger),this._dispatcher=e.attachDispatcher(this)}start(){if(this.isDisposedOrDisposing())throw new Error("Cannot start a disposed circuit.");return this._startPromise||(this._startPromise=this.startCore()),this._startPromise}updateRootComponents(e){var t,n;return this._firstUpdate?(this._firstUpdate=!1,null===(t=this._connection)||void 0===t?void 0:t.send("UpdateRootComponents",e,this._applicationState)):null===(n=this._connection)||void 0===n?void 0:n.send("UpdateRootComponents",e,"")}async startCore(){if(this._connection=await this.startConnection(),this._connection.state!==rn.Connected)return!1;const e=JSON.stringify(this._componentManager.initialComponents.map((e=>At(e))));return this._circuitId=await this._connection.invoke("StartCircuit",We.getBaseURI(),We.getLocationHref(),e,this._applicationState||""),!!this._circuitId}async startConnection(){var e,t;const n=new go;n.name="blazorpack";const o=(new xn).withUrl("_blazor").withHubProtocol(n);this._options.configureSignalR(o);const r=o.build();r.on("JS.AttachComponent",((e,t)=>Ee(Nn.Server,this.resolveElement(t,e),e,!1))),r.on("JS.BeginInvokeJS",this._dispatcher.beginInvokeJSFromDotNet.bind(this._dispatcher)),r.on("JS.EndInvokeDotNet",this._dispatcher.endInvokeDotNetFromJS.bind(this._dispatcher)),r.on("JS.ReceiveByteArray",this._dispatcher.receiveByteArray.bind(this._dispatcher)),r.on("JS.BeginTransmitStream",(e=>{const t=new ReadableStream({start:t=>{r.stream("SendDotNetStreamToJS",e).subscribe({next:e=>t.enqueue(e),complete:()=>t.close(),error:e=>t.error(e)})}});this._dispatcher.supplyDotNetStream(e,t)})),r.on("JS.RenderBatch",(async(e,t)=>{var n,o;this._logger.log(Mt.Debug,`Received render batch with id ${e} and ${t.byteLength} bytes.`),await this._renderQueue.processBatch(e,t,this._connection),null===(o=(n=this._componentManager).onAfterRenderBatch)||void 0===o||o.call(n,Nn.Server)})),r.on("JS.EndLocationChanging",pt._internal.navigationManager.endLocationChanging),r.onclose((e=>!this._disposed&&!this._renderingFailed&&this._options.reconnectionHandler.onConnectionDown(this._options.reconnectionOptions,e))),r.on("JS.Error",(e=>{this._renderingFailed=!0,this.unhandledError(e),No()}));try{await r.start()}catch(e){if(this.unhandledError(e),"FailedToNegotiateWithServerError"===e.errorType)throw e;No(),e.innerErrors&&(e.innerErrors.some((e=>"UnsupportedTransportError"===e.errorType&&e.transport===bn.WebSockets))?this._logger.log(Mt.Error,"Unable to connect, please ensure you are using an updated browser that supports WebSockets."):e.innerErrors.some((e=>"FailedToStartTransportError"===e.errorType&&e.transport===bn.WebSockets))?this._logger.log(Mt.Error,"Unable to connect, please ensure WebSockets are available. A VPN or proxy may be blocking the connection."):e.innerErrors.some((e=>"DisabledTransportError"===e.errorType&&e.transport===bn.LongPolling))&&this._logger.log(Mt.Error,"Unable to initiate a SignalR connection to the server. This might be because the server is not configured to support WebSockets. For additional details, visit https://aka.ms/blazor-server-websockets-error."))}return(null===(t=null===(e=r.connection)||void 0===e?void 0:e.features)||void 0===t?void 0:t.inherentKeepAlive)&&this._logger.log(Mt.Warning,"Failed to connect via WebSockets, using the Long Polling fallback transport. This may be due to a VPN or proxy blocking the connection. To troubleshoot this, visit https://aka.ms/blazor-server-using-fallback-long-polling."),r}async disconnect(){var e;await(null===(e=this._connection)||void 0===e?void 0:e.stop())}async reconnect(){if(!this._circuitId)throw new Error("Circuit host not initialized.");return this._connection.state===rn.Connected||(this._connection=await this.startConnection(),!!await this._connection.invoke("ConnectCircuit",this._circuitId)&&(this._options.reconnectionHandler.onConnectionUp(),!0))}beginInvokeDotNetFromJS(e,t,n,o,r){this.throwIfDispatchingWhenDisposed(),this._connection.send("BeginInvokeDotNetFromJS",e?e.toString():null,t,n,o||0,r)}endInvokeJSFromDotNet(e,t,n){this.throwIfDispatchingWhenDisposed(),this._connection.send("EndInvokeJSFromDotNet",e,t,n)}sendByteArray(e,t){this.throwIfDispatchingWhenDisposed(),this._connection.send("ReceiveByteArray",e,t)}throwIfDispatchingWhenDisposed(){if(this._disposed)throw new Error("The circuit associated with this dispatcher is no longer available.")}sendLocationChanged(e,t,n){return this._connection.send("OnLocationChanged",e,t,n)}sendLocationChanging(e,t,n,o){return this._connection.send("OnLocationChanging",e,t,n,o)}sendJsDataStream(e,t,n){return function(e,t,n,o){setTimeout((async()=>{let r=5,i=(new Date).valueOf();try{const s=t instanceof Blob?t.size:t.byteLength;let a=0,c=0;for(;a1)await e.send("ReceiveJSDataChunk",n,c,h,null);else{if(!await e.invoke("ReceiveJSDataChunk",n,c,h,null))break;const t=(new Date).valueOf(),o=t-i;i=t,r=Math.max(1,Math.round(500/Math.max(1,o)))}a+=l,c++}}catch(t){await e.send("ReceiveJSDataChunk",n,-1,null,t.toString())}}),0)}(this._connection,e,t,n)}resolveElement(e,t){const n=w(e);if(n)return H(n,!0);const o=Number.parseInt(e);if(!Number.isNaN(o))return $(this._componentManager.resolveRootComponent(o,t));throw new Error(`Invalid sequence number or identifier '${e}'.`)}getRootComponentManager(){return this._componentManager}unhandledError(e){this._logger.log(Mt.Error,e),this.disconnect()}getDisconnectFormData(){const e=new FormData,t=this._circuitId;return e.append("circuitId",t),e}didRenderingFail(){return this._renderingFailed}isDisposedOrDisposing(){return void 0!==this._disposePromise}sendDisconnectBeacon(){if(this._disposed)return;const e=this.getDisconnectFormData();this._disposed=navigator.sendBeacon("_blazor/disconnect",e)}dispose(){return this._disposePromise||(this._disposePromise=this.disposeCore()),this._disposePromise}async disposeCore(){var e;if(!this._startPromise)return void(this._disposed=!0);await this._startPromise,this._disposed=!0,null===(e=this._connection)||void 0===e||e.stop();const t=this.getDisconnectFormData();fetch("_blazor/disconnect",{method:"POST",body:t}),function(e){if(!S.delete(e))throw new Error(`Interop methods are not registered for renderer ${e}`)}(Nn.Server)}}const Po={configureSignalR:e=>{},logLevel:ft.Warning,reconnectionOptions:{maxRetries:8,retryIntervalMilliseconds:2e4,dialogId:"components-reconnect-modal"}};class Uo{constructor(e,t,n,o){this.maxRetries=t,this.document=n,this.logger=o,this.addedToDom=!1,this.modal=this.document.createElement("div"),this.modal.id=e,this.maxRetries=t,this.modal.style.cssText=["position: fixed","top: 0","right: 0","bottom: 0","left: 0","z-index: 1050","display: none","overflow: hidden","background-color: #fff","opacity: 0.8","text-align: center","font-weight: bold","transition: visibility 0s linear 500ms"].join(";"),this.message=this.document.createElement("h5"),this.message.style.cssText="margin-top: 20px",this.button=this.document.createElement("button"),this.button.style.cssText="margin:5px auto 5px",this.button.textContent="Retry";const r=this.document.createElement("a");r.addEventListener("click",(()=>location.reload())),r.textContent="reload",this.reloadParagraph=this.document.createElement("p"),this.reloadParagraph.textContent="Alternatively, ",this.reloadParagraph.appendChild(r),this.modal.appendChild(this.message),this.modal.appendChild(this.button),this.modal.appendChild(this.reloadParagraph),this.loader=this.getLoader(),this.message.after(this.loader),this.button.addEventListener("click",(async()=>{this.show();try{await pt.reconnect()||this.rejected()}catch(e){this.logger.log(ft.Error,e),this.failed()}}))}show(){this.addedToDom||(this.addedToDom=!0,this.document.body.appendChild(this.modal)),this.modal.style.display="block",this.loader.style.display="inline-block",this.button.style.display="none",this.reloadParagraph.style.display="none",this.message.textContent="Attempting to reconnect to the server...",this.modal.style.visibility="hidden",setTimeout((()=>{this.modal.style.visibility="visible"}),0)}update(e){this.message.textContent=`Attempting to reconnect to the server: ${e} of ${this.maxRetries}`}hide(){this.modal.style.display="none"}failed(){this.button.style.display="block",this.reloadParagraph.style.display="none",this.loader.style.display="none";const e=this.document.createTextNode("Reconnection failed. Try "),t=this.document.createElement("a");t.textContent="reloading",t.setAttribute("href",""),t.addEventListener("click",(()=>location.reload()));const n=this.document.createTextNode(" the page if you're unable to reconnect.");this.message.replaceChildren(e,t,n)}rejected(){this.button.style.display="none",this.reloadParagraph.style.display="none",this.loader.style.display="none";const e=this.document.createTextNode("Could not reconnect to the server. "),t=this.document.createElement("a");t.textContent="Reload",t.setAttribute("href",""),t.addEventListener("click",(()=>location.reload()));const n=this.document.createTextNode(" the page to restore functionality.");this.message.replaceChildren(e,t,n)}getLoader(){const e=this.document.createElement("div");return e.style.cssText=["border: 0.3em solid #f3f3f3","border-top: 0.3em solid #3498db","border-radius: 50%","width: 2em","height: 2em","display: inline-block"].join(";"),e.animate([{transform:"rotate(0deg)"},{transform:"rotate(360deg)"}],{duration:2e3,iterations:1/0}),e}}class Lo{constructor(e,t,n){this.dialog=e,this.maxRetries=t,this.document=n,this.document=n;const o=this.document.getElementById(Lo.MaxRetriesId);o&&(o.innerText=this.maxRetries.toString())}show(){this.removeClasses(),this.dialog.classList.add(Lo.ShowClassName)}update(e){const t=this.document.getElementById(Lo.CurrentAttemptId);t&&(t.innerText=e.toString())}hide(){this.removeClasses(),this.dialog.classList.add(Lo.HideClassName)}failed(){this.removeClasses(),this.dialog.classList.add(Lo.FailedClassName)}rejected(){this.removeClasses(),this.dialog.classList.add(Lo.RejectedClassName)}removeClasses(){this.dialog.classList.remove(Lo.ShowClassName,Lo.HideClassName,Lo.FailedClassName,Lo.RejectedClassName)}}Lo.ShowClassName="components-reconnect-show",Lo.HideClassName="components-reconnect-hide",Lo.FailedClassName="components-reconnect-failed",Lo.RejectedClassName="components-reconnect-rejected",Lo.MaxRetriesId="components-reconnect-max-retries",Lo.CurrentAttemptId="components-reconnect-current-attempt";class Bo{constructor(e,t,n){this._currentReconnectionProcess=null,this._logger=e,this._reconnectionDisplay=t,this._reconnectCallback=n||pt.reconnect}onConnectionDown(e,t){if(!this._reconnectionDisplay){const t=document.getElementById(e.dialogId);this._reconnectionDisplay=t?new Lo(t,e.maxRetries,document):new Uo(e.dialogId,e.maxRetries,document,this._logger)}this._currentReconnectionProcess||(this._currentReconnectionProcess=new Fo(e,this._logger,this._reconnectCallback,this._reconnectionDisplay))}onConnectionUp(){this._currentReconnectionProcess&&(this._currentReconnectionProcess.dispose(),this._currentReconnectionProcess=null)}}class Fo{constructor(e,t,n,o){this.logger=t,this.reconnectCallback=n,this.isDisposed=!1,this.reconnectDisplay=o,this.reconnectDisplay.show(),this.attemptPeriodicReconnection(e)}dispose(){this.isDisposed=!0,this.reconnectDisplay.hide()}async attemptPeriodicReconnection(e){for(let t=0;tFo.MaximumFirstRetryInterval?Fo.MaximumFirstRetryInterval:e.retryIntervalMilliseconds;if(await this.delay(n),this.isDisposed)break;try{return await this.reconnectCallback()?void 0:void this.reconnectDisplay.rejected()}catch(e){this.logger.log(ft.Error,e)}}this.reconnectDisplay.failed()}delay(e){return new Promise((t=>setTimeout(t,e)))}}Fo.MaximumFirstRetryInterval=3e3;class Oo{constructor(){this.afterStartedCallbacks=[]}async importInitializersAsync(e,t){await Promise.all(e.map((e=>async function(e,n){const o=function(e){const t=document.baseURI;return t.endsWith("/")?`${t}${e}`:`${t}/${e}`}(n),r=await import(o);if(void 0===r)return;const{beforeStart:i,afterStarted:s}=r;return s&&e.afterStartedCallbacks.push(s),i?i(...t):void 0}(this,e))))}async invokeAfterStartedCallbacks(e){await k,await Promise.all(this.afterStartedCallbacks.map((t=>t(e))))}}let $o,Ho,jo,Wo,qo,zo=!1;function Jo(e){if(jo)throw new Error("Circuit options have already been configured.");jo=function(e){const t={...Po,...e};return e&&e.reconnectionOptions&&(t.reconnectionOptions={...Po.reconnectionOptions,...e.reconnectionOptions}),t}(e)}function Vo(e){return Ho.updateRootComponents(e)}function Ko(e){return qo=e,qo}var Xo,Go;const Yo=navigator,Qo=Yo.userAgentData&&Yo.userAgentData.brands,Zo=Qo&&Qo.length>0?Qo.some((e=>"Google Chrome"===e.brand||"Microsoft Edge"===e.brand||"Chromium"===e.brand)):window.chrome,er=null!==(Go=null===(Xo=Yo.userAgentData)||void 0===Xo?void 0:Xo.platform)&&void 0!==Go?Go:navigator.platform;function tr(e){return 0!==e.debugLevel&&(Zo||navigator.userAgent.includes("Firefox"))}let nr,or,rr,ir,sr,ar;const cr=Math.pow(2,32),lr=Math.pow(2,21)-1;let hr=null;function dr(e){return or.getI32(e)}const ur={load:function(e,t){return async function(e,t){const{dotnet:n}=await async function(e){if("undefined"==typeof WebAssembly||!WebAssembly.validate)throw new Error("This browser does not support WebAssembly.");let t="_framework/dotnet.js";if(e.loadBootResource){const n="dotnetjs",o=e.loadBootResource(n,"dotnet.js",t,"","js-module-dotnet");if("string"==typeof o)t=o;else if(o)throw new Error(`For a ${n} resource, custom loaders must supply a URI string.`)}const n=new URL(t,document.baseURI).toString();return await import(n)}(e),o=function(e,t){const n={maxParallelDownloads:1e6,enableDownloadRetry:!1,applicationEnvironment:e.environment},o={...window.Module||{},onConfigLoaded:async(n,{invokeLibraryInitializers:o})=>{var r,i;n.environmentVariables||(n.environmentVariables={}),"sharded"===n.globalizationMode&&(n.environmentVariables.__BLAZOR_SHARDED_ICU="1"),pt._internal.getApplicationEnvironment=()=>n.applicationEnvironment,null==t||t(n);const s=[e,null!==(i=null===(r=n.resources)||void 0===r?void 0:r.extensions)&&void 0!==i?i:{}];await o("beforeStart",s)},onDownloadResourceProgress:pr,config:n,disableDotnet6Compatibility:!1,out:gr,err:mr};return o}(e,t);e.applicationCulture&&n.withApplicationCulture(e.applicationCulture),e.environment&&n.withApplicationEnvironment(e.environment),e.loadBootResource&&n.withResourceLoader(e.loadBootResource),n.withModuleConfig(o),e.configureRuntime&&e.configureRuntime(n),ar=await n.create()}(e,t)},start:function(){return async function(){if(!ar)throw new Error("The runtime must be loaded it gets configured.");const{MONO:t,BINDING:n,Module:o,setModuleImports:r,INTERNAL:i,getConfig:s,invokeLibraryInitializers:a}=ar;rr=o,nr=n,or=t,sr=i,function(e){const t=er.match(/^Mac/i)?"Cmd":"Alt";tr(e)&&console.info(`Debugging hotkey: Shift+${t}+D (when application has focus)`),document.addEventListener("keydown",(t=>{t.shiftKey&&(t.metaKey||t.altKey)&&"KeyD"===t.code&&(tr(e)?navigator.userAgent.includes("Firefox")?async function(){const e=await fetch(`_framework/debug?url=${encodeURIComponent(location.href)}&isFirefox=true`);200!==e.status&&console.warn(await e.text())}():Zo?function(){const e=document.createElement("a");e.href=`_framework/debug?url=${encodeURIComponent(location.href)}`,e.target="_blank",e.rel="noopener noreferrer",e.click()}():console.error("Currently, only Microsoft Edge (80+), Google Chrome, or Chromium, are supported for debugging."):console.error("Cannot start debugging, because the application was not compiled with debugging enabled."))}))}(s()),pt.runtime=ar,pt._internal.dotNetCriticalError=mr,r("blazor-internal",{Blazor:{_internal:pt._internal}});const c=await ar.getAssemblyExports("Microsoft.AspNetCore.Components.WebAssembly");return Object.assign(pt._internal,{dotNetExports:{...c.Microsoft.AspNetCore.Components.WebAssembly.Services.DefaultWebAssemblyJSRuntime}}),ir=e.attachDispatcher({beginInvokeDotNetFromJS:(e,t,n,o,r)=>{if(yr(),!o&&!t)throw new Error("Either assemblyName or dotNetObjectId must have a non null value.");const i=o?o.toString():t;pt._internal.dotNetExports.BeginInvokeDotNet(e?e.toString():null,i,n,r)},endInvokeJSFromDotNet:(e,t,n)=>{pt._internal.dotNetExports.EndInvokeJS(n)},sendByteArray:(e,t)=>{pt._internal.dotNetExports.ReceiveByteArrayFromJS(e,t)},invokeDotNetFromJS:(e,t,n,o)=>(yr(),pt._internal.dotNetExports.InvokeDotNet(e||null,t,null!=n?n:0,o))}),{invokeLibraryInitializers:a}}()},callEntryPoint:async function(){try{await ar.runMain(ar.getConfig().mainAssemblyName,[])}catch(e){console.error(e),No()}},toUint8Array:function(e){const t=vr(e),n=dr(t),o=new Uint8Array(n);return o.set(rr.HEAPU8.subarray(t+4,t+4+n)),o},getArrayLength:function(e){return dr(vr(e))},getArrayEntryPtr:function(e,t,n){return vr(e)+4+t*n},getObjectFieldsBaseAddress:function(e){return e+8},readInt16Field:function(e,t){return n=e+(t||0),or.getI16(n);var n},readInt32Field:function(e,t){return dr(e+(t||0))},readUint64Field:function(e,t){return function(e){const t=e>>2,n=rr.HEAPU32[t+1];if(n>lr)throw new Error(`Cannot read uint64 with high order part ${n}, because the result would exceed Number.MAX_SAFE_INTEGER.`);return n*cr+rr.HEAPU32[t]}(e+(t||0))},readFloatField:function(e,t){return n=e+(t||0),or.getF32(n);var n},readObjectField:function(e,t){return dr(e+(t||0))},readStringField:function(e,t,n){const o=dr(e+(t||0));if(0===o)return null;if(n){const e=nr.unbox_mono_obj(o);return"boolean"==typeof e?e?"":null:e}return nr.conv_string(o)},readStructField:function(e,t){return e+(t||0)},beginHeapLock:function(){return yr(),hr=wr.create(),hr},invokeWhenHeapUnlocked:function(e){hr?hr.enqueuePostReleaseAction(e):e()}};function pr(e,t){const n=e/t*100;document.documentElement.style.setProperty("--blazor-load-percentage",`${n}%`),document.documentElement.style.setProperty("--blazor-load-percentage-text",`"${Math.floor(n)}%"`)}const fr=["DEBUGGING ENABLED"],gr=e=>fr.indexOf(e)<0&&console.log(e),mr=e=>{console.error(e||"(null)"),No()};function vr(e){return e+12}function yr(){if(hr)throw new Error("Assertion failed - heap is currently locked")}class wr{enqueuePostReleaseAction(e){this.postReleaseActions||(this.postReleaseActions=[]),this.postReleaseActions.push(e)}release(){var e;if(hr!==this)throw new Error("Trying to release a lock which isn't current");for(sr.mono_wasm_gc_unlock(),hr=null;null===(e=this.postReleaseActions)||void 0===e?void 0:e.length;)this.postReleaseActions.shift()(),yr()}static create(){return sr.mono_wasm_gc_lock(),new wr}}class br{constructor(e){this.batchAddress=e,this.arrayRangeReader=_r,this.arrayBuilderSegmentReader=Er,this.diffReader=Sr,this.editReader=Cr,this.frameReader=Ir}updatedComponents(){return qo.readStructField(this.batchAddress,0)}referenceFrames(){return qo.readStructField(this.batchAddress,_r.structLength)}disposedComponentIds(){return qo.readStructField(this.batchAddress,2*_r.structLength)}disposedEventHandlerIds(){return qo.readStructField(this.batchAddress,3*_r.structLength)}updatedComponentsEntry(e,t){return kr(e,t,Sr.structLength)}referenceFramesEntry(e,t){return kr(e,t,Ir.structLength)}disposedComponentIdsEntry(e,t){const n=kr(e,t,4);return qo.readInt32Field(n)}disposedEventHandlerIdsEntry(e,t){const n=kr(e,t,8);return qo.readUint64Field(n)}}const _r={structLength:8,values:e=>qo.readObjectField(e,0),count:e=>qo.readInt32Field(e,4)},Er={structLength:12,values:e=>{const t=qo.readObjectField(e,0),n=qo.getObjectFieldsBaseAddress(t);return qo.readObjectField(n,0)},offset:e=>qo.readInt32Field(e,4),count:e=>qo.readInt32Field(e,8)},Sr={structLength:4+Er.structLength,componentId:e=>qo.readInt32Field(e,0),edits:e=>qo.readStructField(e,4),editsEntry:(e,t)=>kr(e,t,Cr.structLength)},Cr={structLength:20,editType:e=>qo.readInt32Field(e,0),siblingIndex:e=>qo.readInt32Field(e,4),newTreeIndex:e=>qo.readInt32Field(e,8),moveToSiblingIndex:e=>qo.readInt32Field(e,8),removedAttributeName:e=>qo.readStringField(e,16)},Ir={structLength:36,frameType:e=>qo.readInt16Field(e,4),subtreeLength:e=>qo.readInt32Field(e,8),elementReferenceCaptureId:e=>qo.readStringField(e,16),componentId:e=>qo.readInt32Field(e,12),elementName:e=>qo.readStringField(e,16),textContent:e=>qo.readStringField(e,16),markupContent:e=>qo.readStringField(e,16),attributeName:e=>qo.readStringField(e,16),attributeValue:e=>qo.readStringField(e,24,!0),attributeEventHandlerId:e=>qo.readUint64Field(e,8)};function kr(e,t,n){return qo.getArrayEntryPtr(e,t,n)}class Tr{constructor(e){this.componentManager=e}resolveRegisteredElement(e,t){const n=Number.parseInt(e);if(!Number.isNaN(n))return $(this.componentManager.resolveRootComponent(n,t))}getParameterValues(e){return this.componentManager.initialComponents[e].parameterValues}getParameterDefinitions(e){return this.componentManager.initialComponents[e].parameterDefinitions}getTypeName(e){return this.componentManager.initialComponents[e].typeName}getAssembly(e){return this.componentManager.initialComponents[e].assembly}getCount(){return this.componentManager.initialComponents.length}}let Dr,Rr,Ar,xr=!1,Nr=!1,Mr=!0,Pr=!1;const Ur=new Promise((e=>{Ar=e}));let Lr;const Br=new Promise((e=>{Lr=e}));function Fr(){return null!=Rr||(Rr=(async()=>{const e=null!=Dr?Dr:{},t=null==Dr?void 0:Dr.configureRuntime;e.configureRuntime=e=>{null==t||t(e),Pr&&e.withEnvironmentVariable("__BLAZOR_WEBASSEMBLY_WAIT_FOR_ROOT_COMPONENTS","true")},await ur.load(e,Ar),xr=!0})()),Rr}function Or(){return xr}function $r(t,n,o,r){const i=ur.readStringField(t,0),s=ur.readInt32Field(t,4),a=ur.readStringField(t,8),c=ur.readUint64Field(t,20);if(null!==a){const e=ur.readUint64Field(t,12);if(0!==e)return ir.beginInvokeJSFromDotNet(e,i,a,s,c),0;{const e=ir.invokeJSFromDotNet(i,a,s,c);return null===e?0:nr.js_string_to_mono_string(e)}}{const t=e.findJSFunction(i,c).call(null,n,o,r);switch(s){case e.JSCallResultType.Default:return t;case e.JSCallResultType.JSObjectReference:return e.createJSObjectReference(t).__jsObjectId;case e.JSCallResultType.JSStreamReference:{const n=e.createJSStreamReference(t),o=JSON.stringify(n);return nr.js_string_to_mono_string(o)}case e.JSCallResultType.JSVoidResult:return null;default:throw new Error(`Invalid JS call result type '${s}'.`)}}}function Hr(e,t,n,o,r){return 0!==r?(ir.beginInvokeJSFromDotNet(r,e,o,n,t),null):ir.invokeJSFromDotNet(e,o,n,t)}function jr(e,t,n){ir.endInvokeDotNetFromJS(e,t,n)}function Wr(e,t,n,o){!function(e,t,n,o,r){let i=ut.get(t);if(!i){const n=new ReadableStream({start(e){ut.set(t,e),i=e}});e.supplyDotNetStream(t,n)}r?(i.error(r),ut.delete(t)):0===o?(i.close(),ut.delete(t)):i.enqueue(n.length===o?n:n.subarray(0,o))}(ir,e,t,n,o)}function qr(e,t){ir.receiveByteArray(e,t)}function zr(e,t){t.namespaceURI?e.setAttributeNS(t.namespaceURI,t.name,t.value):e.setAttribute(t.name,t.value)}const Jr="data-permanent";var Vr,Kr;!function(e){e[e.None=0]="None",e[e.Some=1]="Some",e[e.Infinite=2]="Infinite"}(Vr||(Vr={})),function(e){e.Keep="keep",e.Update="update",e.Insert="insert",e.Delete="delete"}(Kr||(Kr={}));class Xr{static create(e,t,n){return 0===t&&n===e.length?e:new Xr(e,t,n)}constructor(e,t,n){this.source=e,this.startIndex=t,this.length=n}item(e){return this.source.item(e+this.startIndex)}forEach(e,t){for(let t=0;t=n&&s>=o&&r(e.item(i),t.item(s))===Vr.None;)i--,s--,a++;return a}(e,t,o,o,n),i=function(e){var t;const n=[];let o=e.length-1,r=(null===(t=e[o])||void 0===t?void 0:t.length)-1;for(;o>0||r>0;){const t=0===o?Kr.Insert:0===r?Kr.Delete:e[o][r];switch(n.unshift(t),t){case Kr.Keep:case Kr.Update:o--,r--;break;case Kr.Insert:r--;break;case Kr.Delete:o--}}return n}(function(e,t,n){const o=[],r=[],i=e.length,s=t.length;if(0===i&&0===s)return[];for(let e=0;e<=i;e++)(o[e]=Array(s+1))[0]=e,r[e]=Array(s+1);const a=o[0];for(let e=1;e<=s;e++)a[e]=e;for(let a=1;a<=i;a++)for(let i=1;i<=s;i++){const s=n(e.item(a-1),t.item(i-1)),c=o[a-1][i]+1,l=o[a][i-1]+1;let h;switch(s){case Vr.None:h=o[a-1][i-1];break;case Vr.Some:h=o[a-1][i-1]+1;break;case Vr.Infinite:h=Number.MAX_VALUE}h{history.pushState(null,"",e),mi(e)}))}function fi(e){Pe()||mi(location.href)}function gi(e){if(Pe()||e.defaultPrevented)return;const t=e.target;if(t instanceof HTMLFormElement){if(!function(e){const t=e.getAttribute("data-enhance");return"string"==typeof t&&""===t||"true"===(null==t?void 0:t.toLowerCase())}(t))return;e.preventDefault();const n=new URL(t.action),o={method:t.method},r=new FormData(t),i=e.submitter;i&&i.name&&r.append(i.name,i.value),"get"===o.method?n.search=new URLSearchParams(r).toString():o.body=r,mi(n.toString(),o)}}async function mi(e,t){Qr=!0,null==Gr||Gr.abort(),Gr=new AbortController;const n=Gr.signal,o=fetch(e,Object.assign({signal:n,mode:"no-cors",headers:{accept:"text/html;blazor-enhanced-nav=on"}},t));if(await async function(e,t,n,o){let r;try{if(r=await e,!r.body)return void n(r,"");const t=r.headers.get("ssr-framing");if(!t){const e=await r.text();return void n(r,e)}let o=!0;await r.body.pipeThrough(new TextDecoderStream).pipeThrough(function(e){let t="";return new TransformStream({transform(n,o){if(t+=n,t.indexOf(e,t.length-n.length-e.length)>=0){const n=t.split(e);n.slice(0,-1).forEach((e=>o.enqueue(e))),t=n[n.length-1]}},flush(e){e.enqueue(t)}})}(`\x3c!--${t}--\x3e`)).pipeTo(new WritableStream({write(e){o?(o=!1,n(r,e)):(e=>{const t=document.createRange().createContextualFragment(e);for(;t.firstChild;)document.body.appendChild(t.firstChild)})(e)}}))}catch(e){if("AbortError"===e.name&&t.aborted)return;throw e}}(o,n,((n,o)=>{const r=!(null==t?void 0:t.method)||"get"===t.method,i=n.status>=200&&n.status<300;if("opaque"===n.type){if(r)return void yi(e);throw new Error("Enhanced navigation does not support making a non-GET request to an endpoint that redirects to an external origin. Avoid enabling enhanced navigation for form posts that may perform external redirections.")}if(i&&"allow"!==n.headers.get("blazor-enhanced-nav")){if(r)return void yi(e);throw new Error("Enhanced navigation does not support making a non-GET request to a non-Blazor endpoint. Avoid enabling enhanced navigation for forms that post to a non-Blazor endpoint.")}n.redirected&&(r?history.replaceState(null,"",n.url):history.pushState(null,"",n.url),e=n.url);const s=n.headers.get("blazor-enhanced-nav-redirect-location");if(s)return void location.replace(s);const a=n.headers.get("content-type");if((null==a?void 0:a.startsWith("text/html"))&&o){const e=(new DOMParser).parseFromString(o,"text/html");ei(document,e),Yr.documentUpdated()}else(null==a?void 0:a.startsWith("text/"))&&o?vi(o):i||o?r?yi(e):vi(`Error: ${t.method} request to ${e} returned non-HTML content of type ${a||"unspecified"}.`):vi(`Error: ${n.status} ${n.statusText}`)})),!n.aborted){const t=e.indexOf("#");if(t>=0){const n=e.substring(t+1),o=document.getElementById(n);null==o||o.scrollIntoView()}Qr=!1,Yr.enhancedNavigationCompleted()}}function vi(e){document.documentElement.textContent=e;const t=document.documentElement.style;t.fontFamily="consolas, monospace",t.whiteSpace="pre-wrap",t.padding="1rem"}function yi(e){history.replaceState(null,"",e+"?"),location.replace(e)}let wi,bi=!0;class _i extends HTMLElement{connectedCallback(){var e;const t=this.parentNode;null===(e=t.parentNode)||void 0===e||e.removeChild(t),t.childNodes.forEach((e=>{if(e instanceof HTMLTemplateElement){const t=e.getAttribute("blazor-component-id");if(t)!function(e,t){const n=function(e){const t=`bl:${e}`,n=document.createNodeIterator(document,NodeFilter.SHOW_COMMENT);let o=null;for(;(o=n.nextNode())&&o.textContent!==t;);if(!o)return null;const r=`/bl:${e}`;let i=null;for(;(i=n.nextNode())&&i.textContent!==r;);return i?{startMarker:o,endMarker:i}:null}(e);if(n){const{startMarker:e,endMarker:o}=n;if(bi)ei({startExclusive:e,endExclusive:o},t);else{const n=o.parentNode,r=new Range;for(r.setStart(e,e.textContent.length),r.setEnd(o,0),r.deleteContents();t.childNodes[0];)n.insertBefore(t.childNodes[0],o)}wi.documentUpdated()}}(t,e.content);else switch(e.getAttribute("type")){case"redirection":const t=Ne(e.content.textContent),n="form-post"===e.getAttribute("from");"true"===e.getAttribute("enhanced")&&Re(t)?(n?history.pushState(null,"",t):history.replaceState(null,"",t),mi(t)):n?location.assign(t):location.replace(t);break;case"error":vi(e.content.textContent||"Error")}}}))}}class Ei{constructor(e){var t;this._circuitInactivityTimeoutMs=e,this._rootComponents=new Set,this._descriptors=new Set,this._pendingComponentsToResolve=new Map,this._didWebAssemblyFailToLoadQuickly=!1,this._isComponentRefreshPending=!1,this.initialComponents=[],t=()=>{this.rootComponentsMayRequireRefresh()},C.push(t)}onAfterRenderBatch(e){e===Nn.Server&&this.circuitMayHaveNoRootComponents()}onDocumentUpdated(){this.rootComponentsMayRequireRefresh()}onEnhancedNavigationCompleted(){this.rootComponentsMayRequireRefresh()}registerComponent(e){this._descriptors.has(e)||("auto"!==e.type&&"webassembly"!==e.type||this.startLoadingWebAssemblyIfNotStarted(),this._descriptors.add(e),this._rootComponents.add({descriptor:e}))}unregisterComponent(e){this._descriptors.delete(e.descriptor),this._rootComponents.delete(e)}async startLoadingWebAssemblyIfNotStarted(){if(void 0!==Rr)return;Pr=!0;const e=Fr();setTimeout((()=>{Or()||this.onWebAssemblyFailedToLoadQuickly()}),pt._internal.loadWebAssemblyQuicklyTimeout);const t=await Ur;(function(e){if(!e.cacheBootResources)return!1;const t=Si(e);if(!t)return!1;const n=window.localStorage.getItem(t.key);return t.value===n})(t)||this.onWebAssemblyFailedToLoadQuickly(),await e,function(e){const t=Si(e);t&&window.localStorage.setItem(t.key,t.value)}(t),this.rootComponentsMayRequireRefresh()}onWebAssemblyFailedToLoadQuickly(){this._didWebAssemblyFailToLoadQuickly||(this._didWebAssemblyFailToLoadQuickly=!0,this.rootComponentsMayRequireRefresh())}startCircutIfNotStarted(){return zo?Ho.isDisposedOrDisposing()?function(){if(!zo)throw new Error("Cannot start the circuit until Blazor Server has started.");return Ho.didRenderingFail()?Promise.resolve(!1):(Ho.isDisposedOrDisposing()&&($o=bt(document)||"",Ho=new Mo(Ho.getRootComponentManager(),$o,jo,Wo)),Ho.start())}():void 0:async function(e){if(zo)throw new Error("Blazor Server has already started.");zo=!0,$o=bt(document)||"",Wo=new mt(jo.logLevel),Ho=new Mo(e,$o,jo,Wo),Wo.log(ft.Information,"Starting up Blazor server-side application."),pt.reconnect=async()=>!(Ho.didRenderingFail()||!await Ho.reconnect()&&(Wo.log(ft.Information,"Reconnection attempt to the circuit was rejected by the server. This may indicate that the associated state is no longer available on the server."),1)),pt.defaultReconnectionHandler=new Bo(Wo),jo.reconnectionHandler=jo.reconnectionHandler||pt.defaultReconnectionHandler,pt._internal.navigationManager.listenForNavigationEvents(((e,t,n)=>Ho.sendLocationChanged(e,t,n)),((e,t,n,o)=>Ho.sendLocationChanging(e,t,n,o))),pt._internal.forceCloseConnection=()=>Ho.disconnect(),pt._internal.sendJSDataStream=(e,t,n)=>Ho.sendJsDataStream(e,t,n);const t=await async function(e){const t=await fetch("_blazor/initializers",{method:"GET",credentials:"include",cache:"no-cache"}),n=await t.json(),o=new Oo;return await o.importInitializersAsync(n,[e]),o}(jo);if(!await Ho.start())return void Wo.log(ft.Error,"Failed to start the circuit.");const n=()=>{Ho.sendDisconnectBeacon()};pt.disconnect=n,window.addEventListener("unload",n,{capture:!1,once:!0}),Wo.log(ft.Information,"Blazor server-side application started."),t.invokeAfterStartedCallbacks(pt)}(this)}async startWebAssemblyIfNotStarted(){this.startLoadingWebAssemblyIfNotStarted(),Nr||await async function(e){if(Nr)throw new Error("Blazor WebAssembly has already started.");Nr=!0,function(){if(window.parent!==window&&!window.opener&&window.frameElement){const e=window.sessionStorage&&window.sessionStorage["Microsoft.AspNetCore.Components.WebAssembly.Authentication.CachedAuthSettings"],t=e&&JSON.parse(e);return t&&t.redirect_uri&&location.href.startsWith(t.redirect_uri)}return!1}()&&await new Promise((()=>{}));const t=Fr();!function(e){const t=R;R=(e,n,o)=>{((e,t,n)=>{const o=Se(e);(null==o?void 0:o.eventDelegator.getHandler(t))&&ur.invokeWhenHeapUnlocked(n)})(e,n,(()=>t(e,n,o)))}}(),pt._internal.applyHotReload=(e,t,n,o)=>{ir.invokeDotNetStaticMethod("Microsoft.AspNetCore.Components.WebAssembly","ApplyHotReloadDelta",e,t,n,o)},pt._internal.getApplyUpdateCapabilities=()=>ir.invokeDotNetStaticMethod("Microsoft.AspNetCore.Components.WebAssembly","GetApplyUpdateCapabilities"),pt._internal.invokeJSFromDotNet=$r,pt._internal.invokeJSJson=Hr,pt._internal.endInvokeDotNetFromJS=jr,pt._internal.receiveWebAssemblyDotNetDataStream=Wr,pt._internal.receiveByteArray=qr;const n=Ko(ur);pt.platform=n,pt._internal.renderBatch=(e,t)=>{const n=ur.beginHeapLock();try{Ce(e,new br(t))}finally{n.release()}},pt._internal.navigationManager.listenForNavigationEvents((async(e,t,n)=>{await ir.invokeDotNetStaticMethodAsync("Microsoft.AspNetCore.Components.WebAssembly","NotifyLocationChanged",e,t,n)}),(async(e,t,n,o)=>{const r=await ir.invokeDotNetStaticMethodAsync("Microsoft.AspNetCore.Components.WebAssembly","NotifyLocationChangingAsync",t,n,o);pt._internal.navigationManager.endLocationChanging(e,r)}));const o=new Tr(e);let r;pt._internal.registeredComponents={getRegisteredComponentsCount:()=>o.getCount(),getAssembly:e=>o.getAssembly(e),getTypeName:e=>o.getTypeName(e),getParameterDefinitions:e=>o.getParameterDefinitions(e)||"",getParameterValues:e=>o.getParameterValues(e)||""},pt._internal.getPersistedState=()=>_t(document,wt)||"",pt._internal.getInitialComponentsUpdate=()=>Br,pt._internal.updateRootComponents=e=>{var t;return null===(t=pt._internal.dotNetExports)||void 0===t?void 0:t.UpdateRootComponentsCore(e)},pt._internal.attachRootComponentToElement=(e,t,n)=>{const r=o.resolveRegisteredElement(e,t);r?Ee(n,r,t,!1):function(e,t,n){const o="::before";let r=!1;if(e.endsWith("::after"))e=e.slice(0,-7),r=!0;else if(e.endsWith(o))throw new Error(`The '${o}' selector is not supported.`);const i=w(e)||document.querySelector(e);if(!i)throw new Error(`Could not find any element matching selector '${e}'.`);Ee(n||0,H(i,!0),t,r)}(e,t,n)};try{await t,r=await n.start()}catch(e){throw new Error(`Failed to start platform. Reason: ${e}`)}n.callEntryPoint(),r.invokeLibraryInitializers("afterStarted",[pt])}(this)}rootComponentsMayRequireRefresh(){this._isComponentRefreshPending||(this._isComponentRefreshPending=!0,setTimeout((()=>{this._isComponentRefreshPending=!1,this.refreshRootComponents(this._rootComponents)}),0))}circuitMayHaveNoRootComponents(){if(this.hasAnyExistingOrPendingServerComponents())return clearTimeout(this._circuitInactivityTimeoutId),void(this._circuitInactivityTimeoutId=void 0);void 0===this._circuitInactivityTimeoutId&&(this._circuitInactivityTimeoutId=setTimeout((()=>{this.hasAnyExistingOrPendingServerComponents()||(async function(){await(null==Ho?void 0:Ho.dispose())}(),this._circuitInactivityTimeoutId=void 0)}),this._circuitInactivityTimeoutMs))}hasAnyExistingOrPendingServerComponents(){const e=Se(Nn.Server);if(e&&e.getRootComponentCount()>0)return!0;for(const{descriptor:{type:e},assignedRendererId:t}of this._rootComponents){if(t===Nn.Server)return!0;if(void 0===t&&("auto"===e||"server"===e))return!0}return!1}refreshRootComponents(e){const t=new Map;for(const n of e){const e=this.determinePendingOperation(n);if(!e)continue;const o=n.assignedRendererId;if(!o)throw new Error("Descriptors must be assigned a renderer ID before getting used as root components");let r=t.get(o);r||(r=[],t.set(o,r)),r.push(e)}for(const[e,n]of t){const t=JSON.stringify(n);e===Nn.Server?Vo(t):this.updateWebAssemblyRootComponents(t)}this.circuitMayHaveNoRootComponents()}updateWebAssemblyRootComponents(e){Mr?(Lr(e),Mr=!1):function(e){if(!Nr)throw new Error("Blazor WebAssembly has not started.");if(!pt._internal.updateRootComponents)throw new Error("Blazor WebAssembly has not initialized.");pt._internal.updateRootComponents(e)}(e)}resolveRendererIdForDescriptor(e){switch("auto"===e.type?this.getAutoRenderMode():e.type){case"server":return this.startCircutIfNotStarted(),Nn.Server;case"webassembly":return this.startWebAssemblyIfNotStarted(),Nn.WebAssembly;case null:return null}}getAutoRenderMode(){return Or()?"webassembly":this._didWebAssemblyFailToLoadQuickly?"server":null}determinePendingOperation(e){if(n=e.descriptor,document.contains(n.start)){if(void 0===e.assignedRendererId){if(Qr||"loading"===document.readyState)return null;const n=this.resolveRendererIdForDescriptor(e.descriptor);return null===n?null:(t=n,S.has(t)?(e.assignedRendererId=n,e.uniqueIdAtLastUpdate=e.descriptor.uniqueId,this._pendingComponentsToResolve.set(e.descriptor.uniqueId,e),{type:"add",selectorId:e.descriptor.uniqueId,marker:At(e.descriptor)}):null)}if(e.uniqueIdAtLastUpdate===e.descriptor.uniqueId)return null;if(void 0!==e.interactiveComponentId)return e.uniqueIdAtLastUpdate=e.descriptor.uniqueId,{type:"update",componentId:e.interactiveComponentId,marker:At(e.descriptor)}}else{if(this.unregisterComponent(e),void 0!==e.assignedRendererId&&void 0!==e.interactiveComponentId){const t=Se(e.assignedRendererId);null==t||t.disposeComponent(e.interactiveComponentId)}if(void 0!==e.interactiveComponentId)return{type:"remove",componentId:e.interactiveComponentId}}var t,n;return null}resolveRootComponent(e,t){const n=this._pendingComponentsToResolve.get(e);if(!n)throw new Error(`Could not resolve a root component for descriptor with ID '${e}'.`);if(this._pendingComponentsToResolve.delete(e),void 0!==n.interactiveComponentId)throw new Error("Cannot resolve a root component for the same descriptor multiple times.");return n.interactiveComponentId=t,this.refreshRootComponents([n]),n.descriptor}}function Si(e){var t;const n=null===(t=e.resources)||void 0===t?void 0:t.hash,o=e.mainAssemblyName;return n&&o?{key:`blazor-resource-hash:${o}`,value:n}:null}class Ci{constructor(){this._eventListeners=new Map}static create(e){const t=new Ci;return e.addEventListener=t.addEventListener.bind(t),e.removeEventListener=t.removeEventListener.bind(t),t}addEventListener(e,t){let n=this._eventListeners.get(e);n||(n=new Set,this._eventListeners.set(e,n)),n.add(t)}removeEventListener(e,t){var n;null===(n=this._eventListeners.get(e))||void 0===n||n.delete(t)}dispatchEvent(e,t){const n=this._eventListeners.get(e);if(!n)return;const o={...t,type:e};for(const e of n)e(o)}}let Ii,ki=!1;function Ti(e){var t,n,o;if(ki)throw new Error("Blazor has already started.");ki=!0,pt._internal.loadWebAssemblyQuicklyTimeout=3e3,pt._internal.hotReloadApplied=()=>{Ae()&&xe(location.href,!0)},Jo(null==e?void 0:e.circuit),function(e){if(Dr)throw new Error("WebAssembly options have already been configured.");Dr=e}(null==e?void 0:e.webAssembly),Ii=new Ei(null!==(n=null===(t=null==e?void 0:e.ssr)||void 0===t?void 0:t.circuitInactivityTimeoutMs)&&void 0!==n?n:2e3);const r=Ci.create(pt),i={documentUpdated:()=>{Ii.onDocumentUpdated(),r.dispatchEvent("enhancedload",{})},enhancedNavigationCompleted(){Ii.onEnhancedNavigationCompleted()}};return Zr=Ii,function(e,t){wi=t,(null==e?void 0:e.disableDomPreservation)&&(bi=!1),customElements.define("blazor-ssr-end",_i)}(null==e?void 0:e.ssr,i),(null===(o=null==e?void 0:e.ssr)||void 0===o?void 0:o.disableDomPreservation)||di(i),"loading"===document.readyState?document.addEventListener("DOMContentLoaded",Di):Di(),Promise.resolve()}function Di(){!function(e){const t=si(document);for(const e of t)null==Zr||Zr.registerComponent(e)}(),Ii.onDocumentUpdated()}pt.start=Ti,window.DotNet=e,document&&document.currentScript&&"false"!==document.currentScript.getAttribute("autostart")&&Ti()})()})(); \ No newline at end of file diff --git a/src/Components/Web.JS/src/Boot.Server.Common.ts b/src/Components/Web.JS/src/Boot.Server.Common.ts index 4fe93661b2d5..03e6c1c065a5 100644 --- a/src/Components/Web.JS/src/Boot.Server.Common.ts +++ b/src/Components/Web.JS/src/Boot.Server.Common.ts @@ -7,7 +7,7 @@ import { LogLevel } from './Platform/Logging/Logger'; import { CircuitManager } from './Platform/Circuits/CircuitManager'; import { resolveOptions, CircuitStartOptions } from './Platform/Circuits/CircuitStartOptions'; import { DefaultReconnectionHandler } from './Platform/Circuits/DefaultReconnectionHandler'; -import { discoverPersistedState, ServerComponentDescriptor } from './Services/ComponentDescriptorDiscovery'; +import { discoverServerPersistedState, ServerComponentDescriptor } from './Services/ComponentDescriptorDiscovery'; import { fetchAndInvokeInitializers } from './JSInitializers/JSInitializers.Server'; import { RootComponentManager } from './Services/RootComponentManager'; @@ -31,7 +31,7 @@ export async function startServer(components: RootComponentManager circuit.sendJsDataStream(data, streamId, chunkSize); const jsInitializer = await fetchAndInvokeInitializers(options); + const circuitStarted = await circuit.start(); if (!circuitStarted) { logger.log(LogLevel.Error, 'Failed to start the circuit.'); @@ -97,6 +98,7 @@ export function startCircuit(): Promise { if (circuit.isDisposedOrDisposing()) { // If the current circuit is no longer available, create a new one. + appState = discoverServerPersistedState(document) || ''; circuit = new CircuitManager(circuit.getRootComponentManager(), appState, options, logger); } @@ -116,3 +118,7 @@ export async function disposeCircuit() { export function isCircuitAvailable(): boolean { return !circuit.isDisposedOrDisposing(); } + +export function updateServerRootComponents(operations: string): Promise|undefined { + return circuit.updateRootComponents(operations); +} diff --git a/src/Components/Web.JS/src/Boot.WebAssembly.Common.ts b/src/Components/Web.JS/src/Boot.WebAssembly.Common.ts index 339d6863f7eb..79620af2c303 100644 --- a/src/Components/Web.JS/src/Boot.WebAssembly.Common.ts +++ b/src/Components/Web.JS/src/Boot.WebAssembly.Common.ts @@ -11,7 +11,7 @@ import { SharedMemoryRenderBatch } from './Rendering/RenderBatch/SharedMemoryRen import { PlatformApi, Pointer } from './Platform/Platform'; import { WebAssemblyStartOptions } from './Platform/WebAssemblyStartOptions'; import { addDispatchEventMiddleware } from './Rendering/WebRendererInteropMethods'; -import { WebAssemblyComponentDescriptor, discoverPersistedState } from './Services/ComponentDescriptorDiscovery'; +import { WebAssemblyComponentDescriptor, discoverWebAssemblyPersistedState } from './Services/ComponentDescriptorDiscovery'; import { receiveDotNetDataStream } from './StreamingInterop'; import { WebAssemblyComponentAttacher } from './Platform/WebAssemblyComponentAttacher'; import { MonoConfig } from 'dotnet'; @@ -21,12 +21,32 @@ let options: Partial | undefined; let platformLoadPromise: Promise | undefined; let loadedWebAssemblyPlatform = false; let started = false; +let firstUpdate = true; +let waitForRootComponents = false; let resolveBootConfigPromise: (value: MonoConfig) => void; const bootConfigPromise = new Promise(resolve => { resolveBootConfigPromise = resolve; }); +let resolveInitialUpdatePromise: (value: string) => void; +const initialUpdatePromise = new Promise(resolve => { + resolveInitialUpdatePromise = resolve; +}); + +export function resolveInitialUpdate(value: string): void { + resolveInitialUpdatePromise(value); + firstUpdate = false; +} + +export function isFirstUpdate() { + return firstUpdate; +} + +export function setWaitForRootComponents(): void { + waitForRootComponents = true; +} + export function setWebAssemblyOptions(webAssemblyOptions?: Partial) { if (options) { throw new Error('WebAssembly options have already been configured.'); @@ -121,7 +141,12 @@ export async function startWebAssembly(components: RootComponentManager componentAttacher.getParameterValues(id) || '', }; - Blazor._internal.getPersistedState = () => discoverPersistedState(document) || ''; + Blazor._internal.getPersistedState = () => discoverWebAssemblyPersistedState(document) || ''; + + Blazor._internal.getInitialComponentsUpdate = () => initialUpdatePromise; + + Blazor._internal.updateRootComponents = (operations: string) => + Blazor._internal.dotNetExports?.UpdateRootComponentsCore(operations); Blazor._internal.attachRootComponentToElement = (selector, componentId, rendererId: any) => { const element = componentAttacher.resolveRegisteredElement(selector, componentId); @@ -157,7 +182,15 @@ export function waitForBootConfigLoaded(): Promise { export function loadWebAssemblyPlatformIfNotStarted(): Promise { platformLoadPromise ??= (async () => { - await monoPlatform.load(options ?? {}, resolveBootConfigPromise); + const finalOptions = options ?? {}; + const existingConfig = options?.configureRuntime; + finalOptions.configureRuntime = (config) => { + existingConfig?.(config); + if (waitForRootComponents) { + config.withEnvironmentVariable('__BLAZOR_WEBASSEMBLY_WAIT_FOR_ROOT_COMPONENTS', 'true'); + } + }; + await monoPlatform.load(finalOptions, resolveBootConfigPromise); loadedWebAssemblyPlatform = true; })(); return platformLoadPromise; @@ -210,6 +243,18 @@ function invokeJSFromDotNet(callInfo: Pointer, arg0: any, arg1: any, arg2: any): } } +export function updateWebAssemblyRootComponents(operations: string): void { + if (!started) { + throw new Error('Blazor WebAssembly has not started.'); + } + + if (!Blazor._internal.updateRootComponents) { + throw new Error('Blazor WebAssembly has not initialized.'); + } + + Blazor._internal.updateRootComponents(operations); +} + function invokeJSJson(identifier: string, targetInstanceId: number, resultType: number, argsJson: string, asyncHandle: number): string | null { if (asyncHandle !== 0) { dispatcher.beginInvokeJSFromDotNet(asyncHandle, identifier, argsJson, resultType, targetInstanceId); diff --git a/src/Components/Web.JS/src/GlobalExports.ts b/src/Components/Web.JS/src/GlobalExports.ts index 9c94cc0106a0..bbb8676c6437 100644 --- a/src/Components/Web.JS/src/GlobalExports.ts +++ b/src/Components/Web.JS/src/GlobalExports.ts @@ -57,6 +57,8 @@ export interface IBlazor { endInvokeDotNetFromJS?: (callId: string, success: boolean, resultJsonOrErrorMessage: string) => void; receiveByteArray?: (id: number, data: Uint8Array) => void; getPersistedState?: () => string; + getInitialComponentsUpdate?: () => Promise; + updateRootComponents?: (operations: string) => void; attachRootComponentToElement?: (arg0: any, arg1: any, arg2: any, arg3: any) => void; registeredComponents?: { getRegisteredComponentsCount: () => number; @@ -84,6 +86,7 @@ export interface IBlazor { EndInvokeJS: (argsJson: string) => void; BeginInvokeDotNet: (callId: string | null, assemblyNameOrDotNetObjectId: string, methodIdentifier: string, argsJson: string) => void; ReceiveByteArrayFromJS: (id: number, data: Uint8Array) => void; + UpdateRootComponentsCore: (operationsJson: string) => void; } // APIs invoked by hot reload diff --git a/src/Components/Web.JS/src/Platform/Circuits/CircuitManager.ts b/src/Components/Web.JS/src/Platform/Circuits/CircuitManager.ts index e9ba720b095f..8126a2adeddb 100644 --- a/src/Components/Web.JS/src/Platform/Circuits/CircuitManager.ts +++ b/src/Components/Web.JS/src/Platform/Circuits/CircuitManager.ts @@ -22,7 +22,7 @@ import { sendJSDataStream } from './CircuitStreamingInterop'; export class CircuitManager implements DotNet.DotNetCallDispatcher { private readonly _componentManager: RootComponentManager; - private readonly _applicationState: string; + private _applicationState: string; private readonly _options: CircuitStartOptions; @@ -38,6 +38,8 @@ export class CircuitManager implements DotNet.DotNetCallDispatcher { private _startPromise?: Promise; + private _firstUpdate = true; + private _renderingFailed = false; private _disposePromise?: Promise; @@ -71,6 +73,16 @@ export class CircuitManager implements DotNet.DotNetCallDispatcher { return this._startPromise; } + public updateRootComponents(operations: string): Promise | undefined { + if (this._firstUpdate) { + // Only send the application state on the first update. + this._firstUpdate = false; + return this._connection?.send('UpdateRootComponents', operations, this._applicationState); + } else { + return this._connection?.send('UpdateRootComponents', operations, ''); + } + } + private async startCore(): Promise { this._connection = await this.startConnection(); diff --git a/src/Components/Web.JS/src/Services/ComponentDescriptorDiscovery.ts b/src/Components/Web.JS/src/Services/ComponentDescriptorDiscovery.ts index 5fa55303d367..76aeaf292cff 100644 --- a/src/Components/Web.JS/src/Services/ComponentDescriptorDiscovery.ts +++ b/src/Components/Web.JS/src/Services/ComponentDescriptorDiscovery.ts @@ -12,12 +12,21 @@ export function discoverComponents(root: Node, type: 'webassembly' | 'server' | } } -const blazorStateCommentRegularExpression = /^\s*Blazor-Component-State:(?[a-zA-Z0-9+/=]+)$/; +const blazorServerStateCommentRegularExpression = /^\s*Blazor-Server-Component-State:(?[a-zA-Z0-9+/=]+)$/; +const blazorWebAssemblyStateCommentRegularExpression = /^\s*Blazor-WebAssembly-Component-State:(?[a-zA-Z0-9+/=]+)$/; -export function discoverPersistedState(node: Node): string | null | undefined { +export function discoverServerPersistedState(node: Node): string | null | undefined { + return discoverPersistedState(node, blazorServerStateCommentRegularExpression); +} + +export function discoverWebAssemblyPersistedState(node: Node): string | null | undefined { + return discoverPersistedState(node, blazorWebAssemblyStateCommentRegularExpression); +} + +function discoverPersistedState(node: Node, comment: RegExp): string | null | undefined { if (node.nodeType === Node.COMMENT_NODE) { const content = node.textContent || ''; - const parsedState = blazorStateCommentRegularExpression.exec(content); + const parsedState = comment.exec(content); const value = parsedState && parsedState.groups && parsedState.groups['state']; if (value){ node.parentNode?.removeChild(node); @@ -32,7 +41,7 @@ export function discoverPersistedState(node: Node): string | null | undefined { const nodes = node.childNodes; for (let index = 0; index < nodes.length; index++) { const candidate = nodes[index]; - const result = discoverPersistedState(candidate); + const result = discoverPersistedState(candidate, comment); if (result){ return result; } diff --git a/src/Components/Web.JS/src/Services/WebRootComponentManager.ts b/src/Components/Web.JS/src/Services/WebRootComponentManager.ts index 2d925062bd2c..f88171fb9696 100644 --- a/src/Components/Web.JS/src/Services/WebRootComponentManager.ts +++ b/src/Components/Web.JS/src/Services/WebRootComponentManager.ts @@ -2,11 +2,11 @@ // The .NET Foundation licenses this file to you under the MIT license. import { ComponentDescriptor, ComponentMarker, descriptorToMarker } from './ComponentDescriptorDiscovery'; -import { isRendererAttached, registerRendererAttachedListener, updateRootComponents } from '../Rendering/WebRendererInteropMethods'; +import { isRendererAttached, registerRendererAttachedListener } from '../Rendering/WebRendererInteropMethods'; import { WebRendererId } from '../Rendering/WebRendererId'; import { DescriptorHandler } from '../Rendering/DomMerging/DomSync'; -import { disposeCircuit, hasStartedServer, isCircuitAvailable, startCircuit, startServer } from '../Boot.Server.Common'; -import { hasLoadedWebAssemblyPlatform, hasStartedLoadingWebAssemblyPlatform, hasStartedWebAssembly, loadWebAssemblyPlatformIfNotStarted, startWebAssembly, waitForBootConfigLoaded } from '../Boot.WebAssembly.Common'; +import { disposeCircuit, hasStartedServer, isCircuitAvailable, startCircuit, startServer, updateServerRootComponents } from '../Boot.Server.Common'; +import { hasLoadedWebAssemblyPlatform, hasStartedLoadingWebAssemblyPlatform, hasStartedWebAssembly, isFirstUpdate, loadWebAssemblyPlatformIfNotStarted, resolveInitialUpdate, setWaitForRootComponents, startWebAssembly, updateWebAssemblyRootComponents, waitForBootConfigLoaded } from '../Boot.WebAssembly.Common'; import { MonoConfig } from 'dotnet'; import { RootComponentManager } from './RootComponentManager'; import { Blazor } from '../GlobalExports'; @@ -110,6 +110,8 @@ export class WebRootComponentManager implements DescriptorHandler, RootComponent return; } + setWaitForRootComponents(); + const loadWebAssemblyPromise = loadWebAssemblyPlatformIfNotStarted(); // If WebAssembly resources can't be loaded within some time limit, @@ -263,12 +265,24 @@ export class WebRootComponentManager implements DescriptorHandler, RootComponent for (const [rendererId, operations] of operationsByRendererId) { const operationsJson = JSON.stringify(operations); - updateRootComponents(rendererId, operationsJson); + if (rendererId === WebRendererId.Server) { + updateServerRootComponents(operationsJson); + } else { + this.updateWebAssemblyRootComponents(operationsJson); + } } this.circuitMayHaveNoRootComponents(); } + private updateWebAssemblyRootComponents(operationsJson: string) { + if (isFirstUpdate()) { + resolveInitialUpdate(operationsJson); + } else { + updateWebAssemblyRootComponents(operationsJson); + } + } + private resolveRendererIdForDescriptor(descriptor: ComponentDescriptor): WebRendererId | null { const resolvedType = descriptor.type === 'auto' ? this.getAutoRenderMode() : descriptor.type; switch (resolvedType) { @@ -345,6 +359,10 @@ export class WebRootComponentManager implements DescriptorHandler, RootComponent // updates. } else { this.unregisterComponent(component); + if (component.assignedRendererId !== undefined && component.interactiveComponentId !== undefined) { + const renderer = getRendererer(component.assignedRendererId); + renderer?.disposeComponent(component.interactiveComponentId); + } if (component.interactiveComponentId !== undefined) { // We have an interactive component for this marker, so we'll remove it. diff --git a/src/Components/Web/src/PublicAPI.Unshipped.txt b/src/Components/Web/src/PublicAPI.Unshipped.txt index dddd2a2fcceb..8f852bbb2425 100644 --- a/src/Components/Web/src/PublicAPI.Unshipped.txt +++ b/src/Components/Web/src/PublicAPI.Unshipped.txt @@ -123,6 +123,5 @@ static Microsoft.AspNetCore.Components.Web.RenderMode.InteractiveWebAssembly.get virtual Microsoft.AspNetCore.Components.HtmlRendering.Infrastructure.StaticHtmlRenderer.RenderChildComponent(System.IO.TextWriter! output, ref Microsoft.AspNetCore.Components.RenderTree.RenderTreeFrame componentFrame) -> void virtual Microsoft.AspNetCore.Components.HtmlRendering.Infrastructure.StaticHtmlRenderer.WriteComponentHtml(int componentId, System.IO.TextWriter! output) -> void virtual Microsoft.AspNetCore.Components.RenderTree.WebRenderer.GetWebRendererId() -> int -virtual Microsoft.AspNetCore.Components.RenderTree.WebRenderer.UpdateRootComponents(string! operationsJson) -> void Microsoft.AspNetCore.Components.Web.Virtualization.Virtualize.EmptyContent.get -> Microsoft.AspNetCore.Components.RenderFragment? Microsoft.AspNetCore.Components.Web.Virtualization.Virtualize.EmptyContent.set -> void diff --git a/src/Components/Web/src/WebRenderer.cs b/src/Components/Web/src/WebRenderer.cs index 9430f331069a..840369c559c7 100644 --- a/src/Components/Web/src/WebRenderer.cs +++ b/src/Components/Web/src/WebRenderer.cs @@ -85,14 +85,6 @@ protected internal int AddRootComponent([DynamicallyAccessedMembers(Component)] return componentId; } - /// - /// Performs the specified operations on the renderer's root components. - /// - /// A JSON-serialized list of operations to perform on the renderer's root components. - protected virtual void UpdateRootComponents(string operationsJson) - { - } - /// /// Called by the framework to give a location for the specified root component in the browser DOM. /// @@ -123,7 +115,6 @@ internal sealed class WebRendererInteropMethods private readonly JSComponentInterop _jsComponentInterop; [DynamicDependency(nameof(DispatchEventAsync))] - [DynamicDependency(nameof(UpdateRootComponents))] public WebRendererInteropMethods(WebRenderer renderer, JsonSerializerOptions jsonOptions, JSComponentInterop jsComponentInterop) { _renderer = renderer; @@ -141,10 +132,6 @@ public Task DispatchEventAsync(JsonElement eventDescriptor, JsonElement eventArg webEventData.EventArgs); } - [JSInvokable] - public void UpdateRootComponents(string operationsJson) - => _renderer.UpdateRootComponents(operationsJson); - [JSInvokable] // Linker preserves this if you call RootComponents.Add public int AddRootComponent(string identifier, string domElementSelector) => _jsComponentInterop.AddRootComponent(identifier, domElementSelector); diff --git a/src/Components/WebAssembly/WebAssembly/src/Hosting/WebAssemblyHost.cs b/src/Components/WebAssembly/WebAssembly/src/Hosting/WebAssemblyHost.cs index fdc1ffbf5638..a4a1085d8795 100644 --- a/src/Components/WebAssembly/WebAssembly/src/Hosting/WebAssemblyHost.cs +++ b/src/Components/WebAssembly/WebAssembly/src/Hosting/WebAssemblyHost.cs @@ -151,24 +151,47 @@ internal async Task RunAsyncCore(CancellationToken cancellationToken, WebAssembl WebAssemblyNavigationManager.Instance.CreateLogger(loggerFactory); + RootComponentMapping[] mappings = []; + if (Environment.GetEnvironmentVariable("__BLAZOR_WEBASSEMBLY_WAIT_FOR_ROOT_COMPONENTS") == "true") + { + // In Blazor web, we wait for the JS side to tell us about the components available + // before we render the initial set of components. Any additional update goes through + // UpdateRootComponents. + // We do it this way to ensure that the persistent component state is only used the first time + // the wasm runtime is initalized and is done in the same way for both webassembly and blazor + // web. + mappings = await InternalJSImportMethods.GetInitialComponentUpdate(); + } + var initializationTcs = new TaskCompletionSource(); - WebAssemblyCallQueue.Schedule((_rootComponents, _renderer, initializationTcs), static async state => + WebAssemblyCallQueue.Schedule((_rootComponents, _renderer, initializationTcs), async state => { var (rootComponents, renderer, initializationTcs) = state; - try { // Here, we add each root component but don't await the returned tasks so that the // components can be processed in parallel. var count = rootComponents.Count; - var pendingRenders = new Task[count]; + var pendingRenders = new List(count + mappings.Length); for (var i = 0; i < count; i++) { var rootComponent = rootComponents[i]; - pendingRenders[i] = renderer.AddComponentAsync( + pendingRenders.Add(renderer.AddComponentAsync( rootComponent.ComponentType, rootComponent.Parameters, - rootComponent.Selector); + rootComponent.Selector)); + } + + if (mappings != null) + { + for (var i = 0; i < mappings.Length; i++) + { + var rootComponent = mappings[i]; + pendingRenders.Add(renderer.AddComponentAsync( + rootComponent.ComponentType, + rootComponent.Parameters, + rootComponent.Selector)); + } } // Now we wait for all components to finish rendering. diff --git a/src/Components/WebAssembly/WebAssembly/src/Rendering/WebAssemblyRenderer.cs b/src/Components/WebAssembly/WebAssembly/src/Rendering/WebAssemblyRenderer.cs index 29085088e69e..75a7c7285b22 100644 --- a/src/Components/WebAssembly/WebAssembly/src/Rendering/WebAssemblyRenderer.cs +++ b/src/Components/WebAssembly/WebAssembly/src/Rendering/WebAssemblyRenderer.cs @@ -5,7 +5,6 @@ using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices.JavaScript; -using System.Text.Json; using Microsoft.AspNetCore.Components.RenderTree; using Microsoft.AspNetCore.Components.Web; using Microsoft.AspNetCore.Components.Web.Infrastructure; @@ -23,7 +22,6 @@ namespace Microsoft.AspNetCore.Components.WebAssembly.Rendering; /// internal sealed partial class WebAssemblyRenderer : WebRenderer { - private readonly RootComponentTypeCache _rootComponentCache = new(); private readonly ILogger _logger; public WebAssemblyRenderer(IServiceProvider serviceProvider, ILoggerFactory loggerFactory, JSComponentInterop jsComponentInterop) @@ -32,6 +30,28 @@ public WebAssemblyRenderer(IServiceProvider serviceProvider, ILoggerFactory logg _logger = loggerFactory.CreateLogger(); ElementReferenceContext = DefaultWebAssemblyJSRuntime.Instance.ElementReferenceContext; + DefaultWebAssemblyJSRuntime.Instance.OnUpdateRootComponents += OnUpdateRootComponents; + } + + [UnconditionalSuppressMessage("Trimming", "IL2067", Justification = "These are root components which belong to the user and are in assemblies that don't get trimmed.")] + private void OnUpdateRootComponents(OperationDescriptor[] operations) + { + for (var i = 0; i < operations.Length; i++) + { + var (operation, componentType, parameters) = operations[i]; + switch (operation.Type) + { + case RootComponentOperationType.Add: + _ = AddComponentAsync(componentType!, parameters, operation.SelectorId!.Value.ToString(CultureInfo.InvariantCulture)); + break; + case RootComponentOperationType.Update: + _ = RenderRootComponentAsync(operation.ComponentId!.Value, parameters); + break; + case RootComponentOperationType.Remove: + RemoveRootComponent(operation.ComponentId!.Value); + break; + } + } } public override Dispatcher Dispatcher => NullDispatcher.Instance; @@ -53,89 +73,6 @@ protected override void AttachRootComponentToBrowser(int componentId, string dom RendererId); } - [DynamicDependency(JsonSerialized, typeof(RootComponentOperation))] - [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "The correct members will be preserved by the above DynamicDependency")] - protected override void UpdateRootComponents(string operationsJson) - { - var operations = JsonSerializer.Deserialize>( - operationsJson, - WebAssemblyComponentSerializationSettings.JsonSerializationOptions)!; - - foreach (var operation in operations) - { - switch (operation.Type) - { - case RootComponentOperationType.Add: - AddRootComponent(operation); - break; - case RootComponentOperationType.Update: - UpdateRootComponent(operation); - break; - case RootComponentOperationType.Remove: - RemoveRootComponent(operation); - break; - } - } - - return; - - [UnconditionalSuppressMessage("Trimming", "IL2072", Justification = "Root components are expected to be defined in assemblies that do not get trimmed.")] - void AddRootComponent(RootComponentOperation operation) - { - if (operation.SelectorId is not { } selectorId) - { - throw new InvalidOperationException($"The component operation of type '{operation.Type}' requires a '{nameof(operation.SelectorId)}' to be specified."); - } - - if (operation.Marker is not { } marker) - { - throw new InvalidOperationException($"The component operation of type '{operation.Type}' requires a '{nameof(operation.Marker)}' to be specified."); - } - - var componentType = _rootComponentCache.GetRootComponent(marker.Assembly!, marker.TypeName!) - ?? throw new InvalidOperationException($"Root component type '{marker.TypeName}' could not be found in the assembly '{marker.Assembly}'."); - - var parameters = DeserializeComponentParameters(marker); - _ = AddComponentAsync(componentType, parameters, selectorId.ToString(CultureInfo.InvariantCulture)); - } - - void UpdateRootComponent(RootComponentOperation operation) - { - if (operation.ComponentId is not { } componentId) - { - throw new InvalidOperationException($"The component operation of type '{operation.Type}' requires a '{nameof(operation.ComponentId)}' to be specified."); - } - - if (operation.Marker is not { } marker) - { - throw new InvalidOperationException($"The component operation of type '{operation.Type}' requires a '{nameof(operation.Marker)}' to be specified."); - } - - var parameters = DeserializeComponentParameters(marker); - _ = RenderRootComponentAsync(componentId, parameters); - } - - void RemoveRootComponent(RootComponentOperation operation) - { - if (operation.ComponentId is not { } componentId) - { - throw new InvalidOperationException($"The component operation of type '{operation.Type}' requires a '{nameof(operation.ComponentId)}' to be specified."); - } - - this.RemoveRootComponent(componentId); - } - - static ParameterView DeserializeComponentParameters(ComponentMarker marker) - { - var definitions = WebAssemblyComponentParameterDeserializer.GetParameterDefinitions(marker.ParameterDefinitions!); - var values = WebAssemblyComponentParameterDeserializer.GetParameterValues(marker.ParameterValues!); - var componentDeserializer = WebAssemblyComponentParameterDeserializer.Instance; - var parameters = componentDeserializer.DeserializeParameters(definitions, values); - - return parameters; - } - } - /// protected override void Dispose(bool disposing) { diff --git a/src/Components/WebAssembly/WebAssembly/src/Services/DefaultWebAssemblyJSRuntime.cs b/src/Components/WebAssembly/WebAssembly/src/Services/DefaultWebAssemblyJSRuntime.cs index 338f39590fb2..285028d1bf39 100644 --- a/src/Components/WebAssembly/WebAssembly/src/Services/DefaultWebAssemblyJSRuntime.cs +++ b/src/Components/WebAssembly/WebAssembly/src/Services/DefaultWebAssemblyJSRuntime.cs @@ -10,19 +10,24 @@ using Microsoft.JSInterop; using Microsoft.JSInterop.Infrastructure; using Microsoft.JSInterop.WebAssembly; +using static Microsoft.AspNetCore.Internal.LinkerFlags; namespace Microsoft.AspNetCore.Components.WebAssembly.Services; internal sealed partial class DefaultWebAssemblyJSRuntime : WebAssemblyJSRuntime { + private readonly RootComponentTypeCache _rootComponentCache = new(); internal static readonly DefaultWebAssemblyJSRuntime Instance = new(); public ElementReferenceContext ElementReferenceContext { get; } + public event Action? OnUpdateRootComponents; + [DynamicDependency(nameof(InvokeDotNet))] [DynamicDependency(nameof(EndInvokeJS))] [DynamicDependency(nameof(BeginInvokeDotNet))] [DynamicDependency(nameof(ReceiveByteArrayFromJS))] + [DynamicDependency(nameof(UpdateRootComponentsCore))] private DefaultWebAssemblyJSRuntime() { ElementReferenceContext = new WebElementReferenceContext(this); @@ -84,6 +89,83 @@ public static void BeginInvokeDotNet(string? callId, string assemblyNameOrDotNet }); } + [SupportedOSPlatform("browser")] + [JSExport] + public static void UpdateRootComponentsCore(string operationsJson) + { + try + { + var operations = DeserializeOperations(operationsJson); + Instance.OnUpdateRootComponents?.Invoke(operations); + } + catch (Exception ex) + { + Console.Error.WriteLine($"Error deserializing root component operations: {ex}"); + } + } + + [DynamicDependency(JsonSerialized, typeof(RootComponentOperation))] + [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "The correct members will be preserved by the above DynamicDependency")] + [SuppressMessage("Trimming", "IL2072:Target parameter argument does not satisfy 'DynamicallyAccessedMembersAttribute' in call to target method. The return value of the source method does not have matching annotations.", Justification = "Types in that cache are components from the user assembly which are never trimmed.")] + internal static OperationDescriptor[] DeserializeOperations(string operationsJson) + { + var deserialized = JsonSerializer.Deserialize( + operationsJson, + WebAssemblyComponentSerializationSettings.JsonSerializationOptions)!; + + var operations = new OperationDescriptor[deserialized.Length]; + + for (var i = 0; i < deserialized.Length; i++) + { + var operation = deserialized[i]; + if (operation.Type == RootComponentOperationType.Remove || + operation.Type == RootComponentOperationType.Update) + { + if (operation.ComponentId == null) + { + throw new InvalidOperationException($"The component operation of type '{operation.Type}' requires a '{nameof(operation.ComponentId)}' to be specified."); + } + } + + if (operation.Type == RootComponentOperationType.Remove) + { + operations[i] = new(operation, null, ParameterView.Empty); + continue; + } + + if (operation.Marker == null) + { + throw new InvalidOperationException($"The component operation of type '{operation.Type}' requires a '{nameof(operation.Marker)}' to be specified."); + } + + Type? componentType = null; + if (operation.Type == RootComponentOperationType.Add) + { + if (operation.SelectorId == null) + { + throw new InvalidOperationException($"The component operation of type '{operation.Type}' requires a '{nameof(operation.SelectorId)}' to be specified."); + } + componentType = Instance._rootComponentCache.GetRootComponent(operation.Marker!.Value.Assembly!, operation.Marker.Value.TypeName!) + ?? throw new InvalidOperationException($"Root component type '{operation.Marker.Value.TypeName}' could not be found in the assembly '{operation.Marker.Value.Assembly}'."); + } + + var parameters = DeserializeComponentParameters(operation.Marker.Value); + operations[i] = new(operation, componentType, parameters); + } + + return operations; + } + + static ParameterView DeserializeComponentParameters(ComponentMarker marker) + { + var definitions = WebAssemblyComponentParameterDeserializer.GetParameterDefinitions(marker.ParameterDefinitions!); + var values = WebAssemblyComponentParameterDeserializer.GetParameterValues(marker.ParameterValues!); + var componentDeserializer = WebAssemblyComponentParameterDeserializer.Instance; + var parameters = componentDeserializer.DeserializeParameters(definitions, values); + + return parameters; + } + [JSExport] [SupportedOSPlatform("browser")] private static void ReceiveByteArrayFromJS(int id, byte[] data) @@ -101,3 +183,29 @@ protected override Task TransmitStreamAsync(long streamId, DotNetStreamReference return TransmitDataStreamToJS.TransmitStreamAsync(this, "Blazor._internal.receiveWebAssemblyDotNetDataStream", streamId, dotNetStreamReference); } } + +internal readonly struct OperationDescriptor +{ + public OperationDescriptor( + RootComponentOperation operation, + Type? componentType, + ParameterView parameters) + { + Operation = operation; + ComponentType = componentType; + Parameters = parameters; + } + + public RootComponentOperation Operation { get; } + + public Type? ComponentType { get; } + + public ParameterView Parameters { get; } + + public void Deconstruct(out RootComponentOperation operation, out Type? componentType, out ParameterView parameters) + { + operation = Operation; + componentType = ComponentType; + parameters = Parameters; + } +} diff --git a/src/Components/WebAssembly/WebAssembly/src/Services/InternalJSImportMethods.cs b/src/Components/WebAssembly/WebAssembly/src/Services/InternalJSImportMethods.cs index 20c97d2ad2f0..329ece74d556 100644 --- a/src/Components/WebAssembly/WebAssembly/src/Services/InternalJSImportMethods.cs +++ b/src/Components/WebAssembly/WebAssembly/src/Services/InternalJSImportMethods.cs @@ -1,6 +1,8 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using System.Diagnostics.CodeAnalysis; +using System.Globalization; using System.Runtime.InteropServices.JavaScript; using Microsoft.AspNetCore.Components.Web; using Microsoft.AspNetCore.Components.WebAssembly.Hosting; @@ -16,6 +18,29 @@ private InternalJSImportMethods() { } public string GetPersistedState() => GetPersistedStateCore(); + [UnconditionalSuppressMessage("Trimming", "IL2067", Justification = "These are root components which belong to the user and are in assemblies that don't get trimmed.")] + public static async Task GetInitialComponentUpdate() + { + var components = await InternalJSImportMethods.GetInitialUpdateCore(); + var operations = DefaultWebAssemblyJSRuntime.DeserializeOperations(components); + var mappings = new RootComponentMapping[operations.Length]; + + for (var i = 0; i < operations.Length; i++) + { + var (operation, component, parameters) = operations[i]; + if (operation.Type != RootComponentOperationType.Add) + { + throw new InvalidOperationException("All initial operations must be additions."); + } + mappings[i] = new RootComponentMapping( + component!, + operation.SelectorId!.Value.ToString(CultureInfo.InvariantCulture), + parameters); + } + + return mappings; + } + public string GetApplicationEnvironment() => GetApplicationEnvironmentCore(); @@ -52,6 +77,9 @@ public string RegisteredComponents_GetParameterValues(int id) [JSImport("Blazor._internal.getPersistedState", "blazor-internal")] private static partial string GetPersistedStateCore(); + [JSImport("Blazor._internal.getInitialComponentsUpdate", "blazor-internal")] + private static partial Task GetInitialUpdateCore(); + [JSImport("Blazor._internal.getApplicationEnvironment", "blazor-internal")] private static partial string GetApplicationEnvironmentCore(); diff --git a/src/Components/test/E2ETest/ServerRenderingTests/InteractivityTest.cs b/src/Components/test/E2ETest/ServerRenderingTests/InteractivityTest.cs index 3832ba73f372..9feacd3989a4 100644 --- a/src/Components/test/E2ETest/ServerRenderingTests/InteractivityTest.cs +++ b/src/Components/test/E2ETest/ServerRenderingTests/InteractivityTest.cs @@ -847,6 +847,85 @@ public void DotNetObjectReference_CannotBeUsed_AfterCircuitShutsDown_AndANewCirc AssertBrowserLogContainsMessage("Error: The circuit"); } + [Fact] + public void CanPersistPrerenderedState_Server() + { + Navigate($"{ServerPathBase}/persist-state?server=true"); + + Browser.Equal("restored", () => Browser.FindElement(By.Id("server")).Text); + Browser.Equal("Server", () => Browser.FindElement(By.Id("render-mode-server")).Text); + } + + [Fact] + public void CanPersistPrerenderedState_WebAssembly() + { + Navigate($"{ServerPathBase}/persist-state?wasm=true"); + + Browser.Equal("restored", () => Browser.FindElement(By.Id("wasm")).Text); + Browser.Equal("WebAssembly", () => Browser.FindElement(By.Id("render-mode-wasm")).Text); + } + + [Fact] + public void CanPersistPrerenderedState_Auto_PersistsOnWebAssembly() + { + Navigate($"{ServerPathBase}/persist-state?auto=true"); + + Browser.Equal("restored", () => Browser.FindElement(By.Id("auto")).Text); + Browser.Equal("WebAssembly", () => Browser.FindElement(By.Id("render-mode-auto")).Text); + } + + [Fact] + public void CanPersistPrerenderedState_Auto_PersistsOnServer() + { + Navigate(ServerPathBase); + Browser.Equal("Hello", () => Browser.Exists(By.TagName("h1")).Text); + BlockWebAssemblyResourceLoad(); + + Navigate($"{ServerPathBase}/persist-state?auto=true"); + + Browser.Equal("restored", () => Browser.FindElement(By.Id("auto")).Text); + Browser.Equal("Server", () => Browser.FindElement(By.Id("render-mode-auto")).Text); + } + + [Fact] + public void CanPersistState_AllRenderModesAtTheSameTime() + { + Navigate($"{ServerPathBase}/persist-state?server=true&wasm=true&auto=true"); + + Browser.Equal("restored", () => Browser.FindElement(By.Id("server")).Text); + Browser.Equal("Server", () => Browser.FindElement(By.Id("render-mode-server")).Text); + + Browser.Equal("restored", () => Browser.FindElement(By.Id("wasm")).Text); + Browser.Equal("WebAssembly", () => Browser.FindElement(By.Id("render-mode-wasm")).Text); + + Browser.Equal("restored", () => Browser.FindElement(By.Id("auto")).Text); + Browser.Equal("WebAssembly", () => Browser.FindElement(By.Id("render-mode-auto")).Text); + } + + [Fact] + public void CanPersistPrerenderedState_ServerPrerenderedStateAvailableOnlyOnFirstRender() + { + Navigate($"{ServerPathBase}/persist-server-state"); + + Browser.Equal("restored", () => Browser.FindElement(By.Id("server")).Text); + + Browser.Click(By.Id("destroy-and-recreate")); + + Browser.Equal("not restored", () => Browser.FindElement(By.Id("server")).Text); + } + + [Fact] + public void CanPersistPrerenderedState_WebAssemblyPrerenderedStateAvailableOnlyOnFirstRender() + { + Navigate($"{ServerPathBase}/persist-wasm-state"); + + Browser.Equal("restored", () => Browser.FindElement(By.Id("wasm")).Text); + + Browser.Click(By.Id("destroy-and-recreate")); + + Browser.Equal("not restored", () => Browser.FindElement(By.Id("wasm")).Text); + } + private void BlockWebAssemblyResourceLoad() { ((IJavaScriptExecutor)Browser).ExecuteScript("sessionStorage.setItem('block-load-boot-resource', 'true')"); diff --git a/src/Components/test/E2ETest/Tests/SaveStateTest.cs b/src/Components/test/E2ETest/Tests/SaveStateTest.cs index 22439e7e794d..680b030c32c5 100644 --- a/src/Components/test/E2ETest/Tests/SaveStateTest.cs +++ b/src/Components/test/E2ETest/Tests/SaveStateTest.cs @@ -10,6 +10,8 @@ namespace Microsoft.AspNetCore.Components.E2ETest.ServerExecutionTests; +// These tests are for Blazor Server and Webassembly implementations +// For Blazor Web, check StatePersistenceTest.cs public class SaveStateTest : ServerTestBase { public SaveStateTest( diff --git a/src/Components/test/E2ETest/Tests/StatePersistenceTest.cs b/src/Components/test/E2ETest/Tests/StatePersistenceTest.cs new file mode 100644 index 000000000000..9a7dd208bae6 --- /dev/null +++ b/src/Components/test/E2ETest/Tests/StatePersistenceTest.cs @@ -0,0 +1,237 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using Components.TestServer.RazorComponents; +using Microsoft.AspNetCore.Components.E2ETest.Infrastructure; +using Microsoft.AspNetCore.Components.E2ETest.Infrastructure.ServerFixtures; +using Microsoft.AspNetCore.Components.E2ETests.ServerRenderingTests; +using Microsoft.AspNetCore.Components.Web; +using Microsoft.AspNetCore.E2ETesting; +using OpenQA.Selenium; +using TestServer; +using Xunit.Abstractions; + +namespace Microsoft.AspNetCore.Components.E2ETests.Tests; + +// These tests are for Blazor Web implementation +// For Blazor Server and Webassembly, check SaveStateTest.cs +public class StatePersistenceTest : ServerTestBase>> +{ + static int _nextStreamingIdContext; + + public StatePersistenceTest( + BrowserFixture browserFixture, + BasicTestAppServerSiteFixture> serverFixture, + ITestOutputHelper output) + : base(browserFixture, serverFixture, output) + { + } + + // Separate contexts to ensure that caches and other state don't interfere across tests. + public override Task InitializeAsync() + => InitializeAsync(BrowserFixture.StreamingContext + _nextStreamingIdContext++); + + // Validates that we can use persisted state across server, webasembly, and auto modes, with and without + // streaming rendering. + // For streaming rendering, we validate that the state is captured and restored after streaming completes. + // For enhanced navigation we validate that the state is captured at the time components are rendered for + // the first time on the page. + // For auto mode, we validate that the state is captured and restored for both server and wasm runtimes. + // In each case, we validate that the state is available until the initial set of components first render reaches quiescence. Similar to how it works for Server and WebAssembly. + // For server we validate that the state is provided every time a circuit is initialized. + [Theory] + [InlineData(true, typeof(InteractiveServerRenderMode), (string)null)] + [InlineData(true, typeof(InteractiveServerRenderMode), "ServerStreaming")] + [InlineData(true, typeof(InteractiveWebAssemblyRenderMode), (string)null)] + [InlineData(true, typeof(InteractiveWebAssemblyRenderMode), "WebAssemblyStreaming")] + [InlineData(true, typeof(InteractiveAutoRenderMode), (string)null)] + [InlineData(true, typeof(InteractiveAutoRenderMode), "AutoStreaming")] + [InlineData(false, typeof(InteractiveServerRenderMode), (string)null)] + [InlineData(false, typeof(InteractiveServerRenderMode), "ServerStreaming")] + [InlineData(false, typeof(InteractiveWebAssemblyRenderMode), (string)null)] + [InlineData(false, typeof(InteractiveWebAssemblyRenderMode), "WebAssemblyStreaming")] + [InlineData(false, typeof(InteractiveAutoRenderMode), (string)null)] + [InlineData(false, typeof(InteractiveAutoRenderMode), "AutoStreaming")] + public void CanRenderComponentWithPersistedState(bool suppressEnhancedNavigation, Type renderMode, string streaming) + { + var mode = renderMode switch + { + var t when t == typeof(InteractiveServerRenderMode) => "server", + var t when t == typeof(InteractiveWebAssemblyRenderMode) => "wasm", + var t when t == typeof(InteractiveAutoRenderMode) => "auto", + _ => throw new ArgumentException($"Unknown render mode: {renderMode.Name}") + }; + + if (!suppressEnhancedNavigation) + { + // Navigate to a page without components first to make sure that we exercise rendering components + // with enhanced navigation on. + if (streaming == null) + { + Navigate($"subdir/persistent-state/page-no-components?render-mode={mode}&suppress-autostart"); + } + else + { + Navigate($"subdir/persistent-state/page-no-components?render-mode={mode}&streaming-id={streaming}&suppress-autostart"); + } + if (mode == "auto") + { + BlockWebAssemblyResourceLoad(); + } + Browser.Click(By.Id("call-blazor-start")); + Browser.Click(By.Id("page-with-components-link")); + } + else + { + SuppressEnhancedNavigation(true); + } + + if (mode != "auto") + { + RenderComponentsWithPersistentStateAndValidate(suppressEnhancedNavigation, mode, renderMode, streaming); + } + else + { + if (suppressEnhancedNavigation) + { + BlockWebAssemblyResourceLoad(); + } + // For auto mode, validate that the state is persisted for both runtimes and is able + // to be loaded on server and wasm. + RenderComponentsWithPersistentStateAndValidate(suppressEnhancedNavigation, mode, renderMode, streaming, interactiveRuntime: "server"); + + UnblockWebAssemblyResourceLoad(); + Browser.Navigate().Refresh(); + + RenderComponentsWithPersistentStateAndValidate(suppressEnhancedNavigation, mode, renderMode, streaming, interactiveRuntime: "wasm"); + } + } + + [Theory] + [InlineData((string)null)] + [InlineData("ServerStreaming")] + public async Task StateIsProvidedEveryTimeACircuitGetsCreated(string streaming) + { + var mode = "server"; + if (streaming == null) + { + Navigate($"subdir/persistent-state/page-no-components?render-mode={mode}"); + } + else + { + Navigate($"subdir/persistent-state/page-no-components?render-mode={mode}&streaming-id={streaming}"); + } + Browser.Click(By.Id("page-with-components-link")); + + RenderComponentsWithPersistentStateAndValidate(suppresEnhancedNavigation: false, mode, typeof(InteractiveServerRenderMode), streaming); + Browser.Click(By.Id("page-no-components-link")); + // Ensure that the circuit is gone. + await Task.Delay(1000); + Browser.Click(By.Id("page-with-components-link-and-state")); + RenderComponentsWithPersistentStateAndValidate(suppresEnhancedNavigation: false, mode, typeof(InteractiveServerRenderMode), streaming, stateValue: "other"); + } + + private void BlockWebAssemblyResourceLoad() + { + ((IJavaScriptExecutor)Browser).ExecuteScript("sessionStorage.setItem('block-load-boot-resource', 'true')"); + + // Clear caches so that we can block the resource load + ((IJavaScriptExecutor)Browser).ExecuteScript("caches.keys().then(keys => keys.forEach(key => caches.delete(key)))"); + } + + private void UnblockWebAssemblyResourceLoad() + { + ((IJavaScriptExecutor)Browser).ExecuteScript("window.unblockLoadBootResource()"); + } + + private void RenderComponentsWithPersistentStateAndValidate( + bool suppresEnhancedNavigation, + string mode, + Type renderMode, + string streaming, + string interactiveRuntime = null, + string stateValue = null) + { + stateValue ??= "restored"; + // No need to navigate if we are using enhanced navigation, the tests will have already navigated to the page via a link. + if (suppresEnhancedNavigation) + { + // In this case we suppress auto start to check some server side state before we boot Blazor. + if (streaming == null) + { + Navigate($"subdir/persistent-state/page-with-components?render-mode={mode}&suppress-autostart"); + } + else + { + Navigate($"subdir/persistent-state/page-with-components?render-mode={mode}&streaming-id={streaming}&suppress-autostart"); + } + + AssertPageState( + mode: mode, + renderMode: renderMode.Name, + interactive: false, + stateFound: true, + stateValue: stateValue, + streamingId: streaming, + streamingCompleted: false, + interactiveRuntime: interactiveRuntime); + + Browser.Click(By.Id("call-blazor-start")); + } + + AssertPageState( + mode: mode, + renderMode: renderMode.Name, + interactive: streaming == null, + stateFound: true, + stateValue: stateValue, + streamingId: streaming, + streamingCompleted: false, + interactiveRuntime: interactiveRuntime); + + if (streaming != null) + { + Browser.Click(By.Id("end-streaming")); + } + + AssertPageState( + mode: mode, + renderMode: renderMode.Name, + interactive: true, + stateFound: true, + stateValue: stateValue, + streamingId: streaming, + streamingCompleted: true, + interactiveRuntime: interactiveRuntime); + } + + private void AssertPageState( + string mode, + string renderMode, + bool interactive, + bool stateFound, + string stateValue, + string streamingId = null, + bool streamingCompleted = false, + string interactiveRuntime = null) + { + Browser.Equal($"Render mode: {renderMode}", () => Browser.FindElement(By.Id("render-mode")).Text); + Browser.Equal($"Streaming id:{streamingId}", () => Browser.FindElement(By.Id("streaming-id")).Text); + Browser.Equal($"Interactive: {interactive}", () => Browser.FindElement(By.Id("interactive")).Text); + if (streamingId == null || streamingCompleted) + { + interactiveRuntime = !interactive ? "none" : mode == "server" || mode == "wasm" ? mode : (interactiveRuntime ?? throw new InvalidOperationException("Specify interactiveRuntime for auto mode")); + + Browser.Equal($"Interactive runtime: {interactiveRuntime}", () => Browser.FindElement(By.Id("interactive-runtime")).Text); + Browser.Equal($"State found:{stateFound}", () => Browser.FindElement(By.Id("state-found")).Text); + Browser.Equal($"State value:{stateValue}", () => Browser.FindElement(By.Id("state-value")).Text); + } + else + { + Browser.Equal("Streaming: True", () => Browser.FindElement(By.Id("streaming")).Text); + } + } + + private void SuppressEnhancedNavigation(bool shouldSuppress) + => EnhancedNavigationTestUtil.SuppressEnhancedNavigation(this, shouldSuppress); +} diff --git a/src/Components/test/testassets/BasicTestApp/PreserveStateService.cs b/src/Components/test/testassets/BasicTestApp/PreserveStateService.cs index 4a9bfe6d8eeb..b332dfa40e47 100644 --- a/src/Components/test/testassets/BasicTestApp/PreserveStateService.cs +++ b/src/Components/test/testassets/BasicTestApp/PreserveStateService.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.AspNetCore.Components; +using Microsoft.AspNetCore.Components.Web; namespace BasicTestApp; @@ -15,7 +16,7 @@ public class PreserveStateService : IDisposable public PreserveStateService(PersistentComponentState componentApplicationState) { _componentApplicationState = componentApplicationState; - _persistingSubscription = _componentApplicationState.RegisterOnPersisting(PersistState); + _persistingSubscription = _componentApplicationState.RegisterOnPersisting(PersistState, RenderMode.InteractiveAuto); TryRestoreState(); } diff --git a/src/Components/test/testassets/Components.TestServer/RazorComponents/Pages/PersistServerState.razor b/src/Components/test/testassets/Components.TestServer/RazorComponents/Pages/PersistServerState.razor new file mode 100644 index 000000000000..f29bb8e437c0 --- /dev/null +++ b/src/Components/test/testassets/Components.TestServer/RazorComponents/Pages/PersistServerState.razor @@ -0,0 +1,24 @@ +@page "/persist-server-state" +@attribute [RenderModeInteractiveServer] + +

Server Persist State Component

+ +@if (!destroyAndRecreate) +{ + +} +else +{ + +} + + + +@code { + private bool destroyAndRecreate = false; + + private void DestroyAndRecreate() + { + destroyAndRecreate = true; + } +} diff --git a/src/Components/test/testassets/Components.TestServer/RazorComponents/Pages/PersistStateComponents.razor b/src/Components/test/testassets/Components.TestServer/RazorComponents/Pages/PersistStateComponents.razor new file mode 100644 index 000000000000..990fdce136ec --- /dev/null +++ b/src/Components/test/testassets/Components.TestServer/RazorComponents/Pages/PersistStateComponents.razor @@ -0,0 +1,33 @@ +@page "/persist-state" +@using Microsoft.AspNetCore.Components.Web + +

Persist State Components

+ +@if (Server.GetValueOrDefault()) { + Server Persist State Component + +
+} + +@if (WebAssembly.GetValueOrDefault()) { + WebAssembly Persist State Component + +
+} + +@if (Auto.GetValueOrDefault()) { + Auto Persist State Component + +
+} + +@code { + [Parameter, SupplyParameterFromQuery(Name = "server")] + public bool? Server { get; set; } + + [Parameter, SupplyParameterFromQuery(Name = "wasm")] + public bool? WebAssembly { get; set; } + + [Parameter, SupplyParameterFromQuery(Name = "auto")] + public bool? Auto { get; set; } +} diff --git a/src/Components/test/testassets/Components.TestServer/RazorComponents/Pages/PersistentState/EndStreamingPage.razor b/src/Components/test/testassets/Components.TestServer/RazorComponents/Pages/PersistentState/EndStreamingPage.razor new file mode 100644 index 000000000000..e036bf35b067 --- /dev/null +++ b/src/Components/test/testassets/Components.TestServer/RazorComponents/Pages/PersistentState/EndStreamingPage.razor @@ -0,0 +1,36 @@ +@page "/persistent-state/end-streaming" +@using Components.TestServer.Services + +

End streaming page

+ +

This page is used to terminate the streaming rendering operations for + persistent component state tests. It accepts a streaming-id query parameter + which is used to complete streaming on the request with the associated streaming-id. +

+ +

Streaming finished for stream id: @StreamingId

+ + + +@code { + + [SupplyParameterFromQuery(Name = "streaming-id")] public string StreamingId { get; set; } + + [Inject] public AsyncOperationService StreamingManager { get; set; } + + protected override void OnInitialized() + { + if (string.IsNullOrEmpty(StreamingId)) + { + throw new InvalidOperationException("StreamingId is required."); + } + else + { + StreamingManager.Complete(StreamingId); + } + } +} diff --git a/src/Components/test/testassets/Components.TestServer/RazorComponents/Pages/PersistentState/PageWithComponents.razor b/src/Components/test/testassets/Components.TestServer/RazorComponents/Pages/PersistentState/PageWithComponents.razor new file mode 100644 index 000000000000..a03fc598b4ac --- /dev/null +++ b/src/Components/test/testassets/Components.TestServer/RazorComponents/Pages/PersistentState/PageWithComponents.razor @@ -0,0 +1,65 @@ +@page "/persistent-state/page-with-components" +@using TestContentPackage.PersistentComponents + +

Streaming page with components

+ +

+ This page can render one or more components with different render modes and different streaming rendering modes. + It accepts a render-mode query parameter which is used to determine the render mode for the components on the page. + It also accepts a streaming-id query parameter which is used to select whether to render a component that uses streaming rendering or not. +

+ +

Render mode: @_renderMode?.GetType()?.Name

+

Streaming id:@StreamingId

+@if (_renderMode != null) +{ + + @if (!string.IsNullOrEmpty(StreamingId)) + { + + } + else + { + + } + +} +@if (!string.IsNullOrEmpty(StreamingId)) +{ + End streaming +} + +Go to page with no components + + +@code { + + private IComponentRenderMode _renderMode; + + [SupplyParameterFromQuery(Name = "render-mode")] public string RenderMode { get; set; } + + [SupplyParameterFromQuery(Name = "streaming-id")] public string StreamingId { get; set; } + + [SupplyParameterFromQuery(Name = "server-state")] public string ServerState { get; set; } + + protected override void OnInitialized() + { + if (!string.IsNullOrEmpty(RenderMode)) + { + switch (RenderMode) + { + case "server": + _renderMode = new InteractiveServerRenderMode(true); + break; + case "wasm": + _renderMode = new InteractiveWebAssemblyRenderMode(true); + break; + case "auto": + _renderMode = new InteractiveAutoRenderMode(true); + break; + default: + throw new ArgumentException($"Invalid render mode: {RenderMode}"); + } + } + } +} diff --git a/src/Components/test/testassets/Components.TestServer/RazorComponents/Pages/PersistentState/PageWithoutComponents.razor b/src/Components/test/testassets/Components.TestServer/RazorComponents/Pages/PersistentState/PageWithoutComponents.razor new file mode 100644 index 000000000000..674df65314c8 --- /dev/null +++ b/src/Components/test/testassets/Components.TestServer/RazorComponents/Pages/PersistentState/PageWithoutComponents.razor @@ -0,0 +1,14 @@ +@page "/persistent-state/page-no-components" + +

This page does not render any component. We use it to test that persisted state is only provided at the time interactive components get activated on the page.

+ +Go to page with components + +Go to page with components + + +@code { + [SupplyParameterFromQuery(Name = "render-mode")] public string RenderMode { get; set; } + + [SupplyParameterFromQuery(Name = "streaming-id")] public string StreamingId { get; set; } +} diff --git a/src/Components/test/testassets/Components.WasmMinimal/Pages/PersistWebAssemblyState.razor b/src/Components/test/testassets/Components.WasmMinimal/Pages/PersistWebAssemblyState.razor new file mode 100644 index 000000000000..58e39905e2e6 --- /dev/null +++ b/src/Components/test/testassets/Components.WasmMinimal/Pages/PersistWebAssemblyState.razor @@ -0,0 +1,25 @@ +@page "/persist-wasm-state" +@using Microsoft.AspNetCore.Components.Web +@attribute [RenderModeInteractiveWebAssembly] + +

WebAssembly Persist State Component

+ +@if (!destroyAndRecreate) +{ + +} +else +{ + +} + + + +@code { + private bool destroyAndRecreate = false; + + private void DestroyAndRecreate() + { + destroyAndRecreate = true; + } +} diff --git a/src/Components/test/testassets/Components.WasmMinimal/Program.cs b/src/Components/test/testassets/Components.WasmMinimal/Program.cs index 945c94a24a65..f7e7dfa8d56a 100644 --- a/src/Components/test/testassets/Components.WasmMinimal/Program.cs +++ b/src/Components/test/testassets/Components.WasmMinimal/Program.cs @@ -1,10 +1,14 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using System.ComponentModel; using System.Reflection; +using Components.TestServer.Services; using Microsoft.AspNetCore.Components.WebAssembly.Hosting; Assembly.Load(nameof(TestContentPackage)); var builder = WebAssemblyHostBuilder.CreateDefault(args); +builder.Services.AddSingleton(); + await builder.Build().RunAsync(); diff --git a/src/Components/test/testassets/TestContentPackage/PersistStateComponent.razor b/src/Components/test/testassets/TestContentPackage/PersistStateComponent.razor new file mode 100644 index 000000000000..1099acd4261e --- /dev/null +++ b/src/Components/test/testassets/TestContentPackage/PersistStateComponent.razor @@ -0,0 +1,40 @@ +@implements IDisposable +@inject PersistentComponentState ApplicationState + +

Application state is @value

+

Render mode: @_renderMode

+ +@code { + [Parameter, EditorRequired] + public string KeyName { get; set; } = ""; + + private string value = "not started"; + private string _renderMode = "SSR"; + + private PersistingComponentStateSubscription persistingSubscription; + + protected override void OnInitialized() + { + persistingSubscription = ApplicationState.RegisterOnPersisting(() => + { + ApplicationState.PersistAsJson(KeyName, $"restored"); + return Task.CompletedTask; + }); + + if (!ApplicationState.TryTakeFromJson(KeyName, out var restored)) + { + value = "not restored"; + } + else + { + value = restored!; + } + + _renderMode = OperatingSystem.IsBrowser() ? "WebAssembly" : "Server"; + } + + void IDisposable.Dispose() + { + persistingSubscription.Dispose(); + } +} diff --git a/src/Components/test/testassets/TestContentPackage/PersistentComponents/NonStreamingComponentWithPersistentState.razor b/src/Components/test/testassets/TestContentPackage/PersistentComponents/NonStreamingComponentWithPersistentState.razor new file mode 100644 index 000000000000..e54c00a21c36 --- /dev/null +++ b/src/Components/test/testassets/TestContentPackage/PersistentComponents/NonStreamingComponentWithPersistentState.razor @@ -0,0 +1,49 @@ +

Non streaming component with persistent state

+ +

This component demonstrates state persistence in the absence of streaming rendering. When the component renders it will try to restore the state and if present display that it succeded in doing so and the restored value. If the state is not present, it will indicate it didn't find it and display a "fresh" value.

+ +

Interactive: @(!RunningOnServer)

+

Interactive runtime: @_interactiveRuntime

+

State found:@_stateFound

+

State value:@_stateValue

+ +@code { + + private bool _stateFound; + private string _stateValue; + private string _interactiveRuntime; + + [Inject] public PersistentComponentState PersistentComponentState { get; set; } + + [CascadingParameter(Name = nameof(RunningOnServer))] public bool RunningOnServer { get; set; } + [Parameter] public string ServerState { get; set; } + + protected override void OnInitialized() + { + PersistentComponentState.RegisterOnPersisting(PersistState); + + _stateFound = PersistentComponentState.TryTakeFromJson("NonStreamingComponentWithPersistentState", out _stateValue); + + if (!_stateFound) + { + _stateValue = "fresh"; + } + + if (RunningOnServer) + { + _interactiveRuntime = "none"; + _stateFound = true; + _stateValue = ServerState ?? "restored"; + } + else + { + _interactiveRuntime = OperatingSystem.IsBrowser() ? "wasm" : "server"; + } + } + + Task PersistState() + { + PersistentComponentState.PersistAsJson("NonStreamingComponentWithPersistentState", _stateValue); + return Task.CompletedTask; + } +} diff --git a/src/Components/test/testassets/TestContentPackage/PersistentComponents/StreamingComponentWithPersistentState.razor b/src/Components/test/testassets/TestContentPackage/PersistentComponents/StreamingComponentWithPersistentState.razor new file mode 100644 index 000000000000..632a7bd7996c --- /dev/null +++ b/src/Components/test/testassets/TestContentPackage/PersistentComponents/StreamingComponentWithPersistentState.razor @@ -0,0 +1,77 @@ +@using Components.TestServer.Services +@attribute [StreamRendering] +

Streaming component with persistent state

+ +

This component demonstrates state persistence alongside streaming rendering. When the component first renders, it'll emit a message "streaming" and yield until its notified via a call to /persistent-state/end-streaming. When the component renders it will try to restore the state and if present display that it succeded in doing so and the restored value. If the state is not present, it will indicate it didn't find it and display a "fresh" value.

+ +

Interactive: @(!RunningOnServer)

+@if (_streaming) +{ +

Streaming: @_streaming

+} +else +{ +

Interactive runtime: @_interactiveRuntime

+

State found:@_stateFound

+

State value:@_stateValue

+} + +@code { + + private bool _streaming; + private bool _stateFound; + private string _stateValue; + private string _interactiveRuntime; + + [Inject] public PersistentComponentState PersistentComponentState { get; set; } + + [Inject] public AsyncOperationService StreamingManager { get; set; } + + [Parameter] public string StreamingId { get; set; } + + [Parameter] public string ServerState { get; set; } + + [CascadingParameter(Name = nameof(RunningOnServer))] public bool RunningOnServer { get; set; } + + protected override async Task OnInitializedAsync() + { + if (string.IsNullOrEmpty(StreamingId)) + { + throw new InvalidOperationException("StreamingId is required."); + } + PersistentComponentState.RegisterOnPersisting(PersistState); + + if (RunningOnServer) + { + _interactiveRuntime = "none"; + _streaming = true; + await StreamingManager.Start(StreamingId); + _streaming = false; + }else + { + _interactiveRuntime = OperatingSystem.IsBrowser() ? "wasm" : "server"; + } + + // We do this to ensure that the state remains accessible during the entire first render + // cycle (technically until the root component reaches quiescence). + await Task.Yield(); + _stateFound = PersistentComponentState.TryTakeFromJson("NonStreamingComponentWithPersistentState", out _stateValue); + + if (!_stateFound) + { + _stateValue = "fresh"; + } + + if (RunningOnServer) + { + _stateFound = true; + _stateValue = ServerState ?? "restored"; + } + } + + Task PersistState() + { + PersistentComponentState.PersistAsJson("NonStreamingComponentWithPersistentState", _stateValue); + return Task.CompletedTask; + } +} diff --git a/src/Components/test/testassets/Components.TestServer/Services/AsyncOperationService.cs b/src/Components/test/testassets/TestContentPackage/Services/AsyncOperationService.cs similarity index 100% rename from src/Components/test/testassets/Components.TestServer/Services/AsyncOperationService.cs rename to src/Components/test/testassets/TestContentPackage/Services/AsyncOperationService.cs diff --git a/src/Mvc/Mvc.TagHelpers/test/PersistComponentStateTagHelperTest.cs b/src/Mvc/Mvc.TagHelpers/test/PersistComponentStateTagHelperTest.cs index e71189162e78..4b90d3afb942 100644 --- a/src/Mvc/Mvc.TagHelpers/test/PersistComponentStateTagHelperTest.cs +++ b/src/Mvc/Mvc.TagHelpers/test/PersistComponentStateTagHelperTest.cs @@ -19,6 +19,7 @@ using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Moq; +using RenderMode = Microsoft.AspNetCore.Components.Web.RenderMode; namespace Microsoft.AspNetCore.Mvc.TagHelpers; @@ -50,6 +51,28 @@ public async Task ExecuteAsync_DoesNotPersistDataWhenNoPrerenderHappened() Assert.Null(output.TagName); } + [Fact] + public async Task ExecuteAsync_DoesNotRenderWebAssemblyStateWhenStateWasNotPersisted() + { + // Arrange + var tagHelper = new PersistComponentStateTagHelper + { + ViewContext = GetViewContext(), + PersistenceMode = PersistenceMode.WebAssembly + }; + + var context = GetTagHelperContext(); + var output = GetTagHelperOutput(); + + // Act + await tagHelper.ProcessAsync(context, output); + + // Assert + var content = HtmlContentUtilities.HtmlContentToString(output.Content); + Assert.Empty(content); + Assert.Null(output.TagName); + } + [Fact] public async Task ExecuteAsync_RendersWebAssemblyStateExplicitly() { @@ -62,14 +85,21 @@ public async Task ExecuteAsync_RendersWebAssemblyStateExplicitly() var context = GetTagHelperContext(); var output = GetTagHelperOutput(); + var manager = tagHelper.ViewContext.HttpContext.RequestServices.GetRequiredService(); // Act + manager.State.RegisterOnPersisting(() => + { + manager.State.PersistAsJson("state", "state value"); + return Task.CompletedTask; + }, RenderMode.InteractiveWebAssembly); await tagHelper.ProcessAsync(context, output); // Assert var content = HtmlContentUtilities.HtmlContentToString(output.Content); - Assert.Equal("", content); Assert.Null(output.TagName); + var message = content["".Length]; + Assert.True(message.Length > 0); } [Fact] @@ -81,18 +111,25 @@ public async Task ExecuteAsync_RendersWebAssemblyStateImplicitlyWhenAWebAssembly ViewContext = GetViewContext() }; - EndpointHtmlRenderer.UpdateSaveStateRenderMode(tagHelper.ViewContext.HttpContext, Components.Web.RenderMode.InteractiveWebAssembly); + EndpointHtmlRenderer.UpdateSaveStateRenderMode(tagHelper.ViewContext.HttpContext, RenderMode.InteractiveWebAssembly); var context = GetTagHelperContext(); var output = GetTagHelperOutput(); + var manager = tagHelper.ViewContext.HttpContext.RequestServices.GetRequiredService(); // Act + manager.State.RegisterOnPersisting(() => + { + manager.State.PersistAsJson("state", "state value"); + return Task.CompletedTask; + }, RenderMode.InteractiveWebAssembly); await tagHelper.ProcessAsync(context, output); // Assert var content = HtmlContentUtilities.HtmlContentToString(output.Content); - Assert.Equal("", content); Assert.Null(output.TagName); + var message = content["".Length]; + Assert.True(message.Length > 0); } [Fact] @@ -107,17 +144,44 @@ public async Task ExecuteAsync_RendersServerStateExplicitly() var context = GetTagHelperContext(); var output = GetTagHelperOutput(); + var manager = tagHelper.ViewContext.HttpContext.RequestServices.GetRequiredService(); // Act + manager.State.RegisterOnPersisting(() => + { + manager.State.PersistAsJson("state", "state value"); + return Task.CompletedTask; + }, RenderMode.InteractiveServer); + await tagHelper.ProcessAsync(context, output); // Assert var content = HtmlContentUtilities.HtmlContentToString(output.Content); Assert.NotEmpty(content); - var payload = content["".Length]; + var payload = content["".Length]; var message = _protector.Unprotect(payload); - Assert.Equal("{}", message); - Assert.Null(output.TagName); + Assert.True(message.Length > 0); + } + + [Fact] + public async Task ExecuteAsync_DoesNotRenderServerStateWhenStateWasNotPersisted() + { + // Arrange + var tagHelper = new PersistComponentStateTagHelper + { + ViewContext = GetViewContext(), + PersistenceMode = PersistenceMode.Server + }; + + var context = GetTagHelperContext(); + var output = GetTagHelperOutput(); + + // Act + await tagHelper.ProcessAsync(context, output); + + // Assert + var content = HtmlContentUtilities.HtmlContentToString(output.Content); + Assert.Empty(content); } [Fact] @@ -133,16 +197,23 @@ public async Task ExecuteAsync_RendersServerStateImplicitlyWhenAServerComponentW var context = GetTagHelperContext(); var output = GetTagHelperOutput(); + var manager = tagHelper.ViewContext.HttpContext.RequestServices.GetRequiredService(); // Act + manager.State.RegisterOnPersisting(() => + { + manager.State.PersistAsJson("state", "state value"); + return Task.CompletedTask; + }, RenderMode.InteractiveServer); + await tagHelper.ProcessAsync(context, output); // Assert var content = HtmlContentUtilities.HtmlContentToString(output.Content); Assert.NotEmpty(content); - var payload = content["".Length]; + var payload = content["".Length]; var message = _protector.Unprotect(payload); - Assert.Equal("{}", message); + Assert.True(message.Length > 0); } [Fact] diff --git a/src/Shared/Components/PrerenderComponentApplicationStore.cs b/src/Shared/Components/PrerenderComponentApplicationStore.cs index ed56f7f349b9..2c76d4034a1a 100644 --- a/src/Shared/Components/PrerenderComponentApplicationStore.cs +++ b/src/Shared/Components/PrerenderComponentApplicationStore.cs @@ -3,6 +3,7 @@ using System.Diagnostics.CodeAnalysis; using System.Text.Json; +using Microsoft.AspNetCore.Components.Web; namespace Microsoft.AspNetCore.Components; @@ -10,6 +11,8 @@ namespace Microsoft.AspNetCore.Components; internal class PrerenderComponentApplicationStore : IPersistentComponentStateStore #pragma warning restore CA1852 // Seal internal types { + private bool _stateIsPersisted; + public PrerenderComponentApplicationStore() { ExistingState = new(); @@ -52,7 +55,21 @@ protected virtual byte[] SerializeState(IReadOnlyDictionary stat public Task PersistStateAsync(IReadOnlyDictionary state) { - PersistedState = Convert.ToBase64String(SerializeState(state)); + if (_stateIsPersisted) + { + throw new InvalidOperationException("State already persisted."); + } + + _stateIsPersisted = true; + + if (state is not null && state.Count > 0) + { + PersistedState = Convert.ToBase64String(SerializeState(state)); + } + return Task.CompletedTask; } + + public virtual bool SupportsRenderMode(IComponentRenderMode renderMode) => + renderMode is null || renderMode is InteractiveWebAssemblyRenderMode || renderMode is InteractiveAutoRenderMode; } diff --git a/src/Shared/Components/ProtectedPrerenderComponentApplicationStore.cs b/src/Shared/Components/ProtectedPrerenderComponentApplicationStore.cs index aa9cdc3260f2..6025dc48f205 100644 --- a/src/Shared/Components/ProtectedPrerenderComponentApplicationStore.cs +++ b/src/Shared/Components/ProtectedPrerenderComponentApplicationStore.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using Microsoft.AspNetCore.Components.Web; using Microsoft.AspNetCore.DataProtection; namespace Microsoft.AspNetCore.Components; @@ -28,4 +29,8 @@ protected override byte[] SerializeState(IReadOnlyDictionary sta private void CreateProtector(IDataProtectionProvider dataProtectionProvider) => _protector = dataProtectionProvider.CreateProtector("Microsoft.AspNetCore.Components.Server.State"); + + public override bool SupportsRenderMode(IComponentRenderMode renderMode) => + renderMode is null || + renderMode is InteractiveServerRenderMode || renderMode is InteractiveAutoRenderMode; } diff --git a/src/Shared/E2ETesting/BrowserFixture.cs b/src/Shared/E2ETesting/BrowserFixture.cs index c8cb527d3e96..67ab36f443b8 100644 --- a/src/Shared/E2ETesting/BrowserFixture.cs +++ b/src/Shared/E2ETesting/BrowserFixture.cs @@ -142,7 +142,7 @@ private async Task DeleteBrowserUserProfileDirectoriesAsync() { var opts = new ChromeOptions(); - if (string.Equals(context, StreamingContext, StringComparison.Ordinal)) + if (context?.StartsWith(StreamingContext, StringComparison.Ordinal) == true) { // Tells Selenium not to wait until the page navigation has completed before continuing with the tests opts.PageLoadStrategy = PageLoadStrategy.None;