using Microsoft.JSInterop;
namespace DeepDrftPublic.Client.Services;
///
/// Production over the window.DeepDrftAnonId TS interop. Reads the
/// first-party localStorage GUID once and caches it for the session, so the synchronous emit paths
/// read it with no JS hop. Scoped (per-session) like the other telemetry collaborators; the underlying
/// token itself outlives the session in localStorage — the cache just avoids repeated interop.
///
public sealed class AnonIdProvider : IAnonIdProvider
{
private readonly IJSRuntime _js;
private bool _loaded;
public AnonIdProvider(IJSRuntime js)
{
_js = js;
}
public string? Current { get; private set; }
public async ValueTask EnsureLoadedAsync()
{
if (_loaded) return;
try
{
// The module returns null when localStorage is unavailable; we store that null and still
// mark loaded so we don't retry every emit. A genuine interop failure (module not yet
// imported, prerender) is caught below and leaves _loaded false so a later warm can succeed.
Current = await _js.InvokeAsync("DeepDrftAnonId.get");
_loaded = true;
}
catch
{
// Interop unavailable (prerender / module not loaded). Leave Current null and unloaded so a
// subsequent warm retries — telemetry simply omits the id until then.
}
}
}