diff --git a/docs/media-showcase.md b/docs/media-showcase.md index a82f904..6d02cce 100644 --- a/docs/media-showcase.md +++ b/docs/media-showcase.md @@ -16,8 +16,8 @@ The recording label sits with the source caption below the player. It does not cover the picture or Safari’s native fullscreen control when controls appear. -The player pins RelaySwarm source `d4a1235b035b4244ea73b55b1da0d4f88f64c376` -([source change](https://github.com/forgesworn/relayswarm/commit/d4a1235b035b4244ea73b55b1da0d4f88f64c376)). +The player pins RelaySwarm source `c8120c5bf8c117e334a37a072b3bd6f3de46cc3a` +([source change](https://github.com/forgesworn/relayswarm/commit/c8120c5bf8c117e334a37a072b3bd6f3de46cc3a)). It retains the successful peer receipt's stats when hls.js disposes of the losing HTTP loader, covered by ten regressions using the actual hls.js 1.7.3 loaders. It also retains a fully verified contiguous future prefix before considering @@ -569,6 +569,17 @@ integrity failures, and peer eligibility. Each count is a nonnegative safe integer or `null`; missing values are not inferred as zero. Raw SDK records, keys, tickets and transfer objects are excluded. Submitted uploads and verified pieces in a losing race do not become accepted peer-media credit. +The separate `peerFlowDiagnostics` observation retains only the SDK's fixed +short-flow batch counts, bytes and latest span, plus model-evaluation counters +and the latest numeric model inputs. Decisions distinguish a fitting measured +piece, useful unknown flow, an allowed refresh, a cooldown-blocked unknown +model and a retained known slow model. Evaluations are not request counts. +The no-model counter records attempts rejected before transfer creation; its +snapshot describes only the latest candidate from that attempt, alongside +the candidate count. Rates, timing and previous snapshots remain `null` when +unobserved. This projection adds no timers, requests, playback credit or +selection policy. It is diagnostic evidence for choosing subsequent tuning, +not a throughput or sustained-playback qualification. These attempt counters describe the current SDK generation and may reset after peer sharing restarts; compare them only within a continuous generation. Terminal handling retains the projected startup flags and geometry; these other current diff --git a/scripts/build-media-peer-demo.mjs b/scripts/build-media-peer-demo.mjs index 999c7df..48a9f4f 100644 --- a/scripts/build-media-peer-demo.mjs +++ b/scripts/build-media-peer-demo.mjs @@ -7,7 +7,7 @@ import { tmpdir } from 'node:os'; import { dirname, join, resolve } from 'node:path'; import { fileURLToPath, pathToFileURL } from 'node:url'; -const SOURCE = 'd4a1235b035b4244ea73b55b1da0d4f88f64c376'; +const SOURCE = 'c8120c5bf8c117e334a37a072b3bd6f3de46cc3a'; const sha = bytes => createHash('sha256').update(bytes).digest('hex'); const root = fileURLToPath(new URL('../', import.meta.url)); diff --git a/site/live-media.html b/site/live-media.html index 8b4f8f1..057d84d 100644 --- a/site/live-media.html +++ b/site/live-media.html @@ -123,6 +123,6 @@ - + diff --git a/site/llms.txt b/site/llms.txt index 9086e9a..0340760 100644 --- a/site/llms.txt +++ b/site/llms.txt @@ -7,8 +7,9 @@ - [Landing page](https://forgesworn.dev/): products you can run today, the creed, and the full repo catalogue grouped into eleven focus areas - [Ecosystem map](https://forgesworn.dev/map/ecosystem-map.svg): every project on one page, grouped by what it does (SVG; printable A4 PDF at https://forgesworn.dev/map/ecosystem-map-a4.pdf) - [Use cases](https://forgesworn.dev/use-cases.html): 32 end-to-end workflows, each naming the exact libraries it composes -- [4K listening room and comparison player](https://forgesworn.dev/media-lab.html): the complete licensed Deja Vu mix leads the homepage. Play & join starts or joins a shared listening clock and real RelaySwarm participation. For a new room, the first full-recording viewer prepares a bounded verified media reservoir locally before publishing the shared start time; preparation does not count as an active listener. A viewer still preparing a private start adopts a verified active room promptly, retires its empty old loader before the acknowledgement and preserves the original Play request; a failed acknowledgement restores an explicit retry. Cancelled or replaced asynchronous setup failures cannot fail a newer Play request; genuine current publication failures still restore retry. Existing rooms keep their advancing clocks and later listeners join live, the starter can leave while others continue, and the room expires after the last listener leaves a short grace period. Pause leaves; Play rejoins live. The recording loops while occupied; the 1080p excerpt has its own room. The live listener ticker includes joined listeners and excludes read-only page observers; Play/Pause events update it directly, with lease expiry for abrupt departures and unknown status during lost room observation. A confirmed empty room invites the first listener to start. One visible player per visitor, room participants distinct from locally connected peers, stable identity mapping through peerConnectionDetails(), proportional media-batch movement and rates, source-host feeds, explicitly self-reported remote links, separate loaded-source/verified-peer/upload counters and recent local peer contribution. Loaded source includes browser cache; playback details distinguish completed source response bodies from network and cache when timing coverage is available. Cache hits do not animate as fresh local network traffic; concealed timings remain unavailable. The browser integration pins RelaySwarm source d4a1235b035b4244ea73b55b1da0d4f88f64c376 (package version 0.4.4), retaining bounded rolling startup planning, sustainable peer waits and range-sized WASM uploads. Startup preserves its verified contiguous future prefix before using the existing fourth residency slot even after the original first interval expires; that contiguous successor is not skipped by the previous fragment’s service-time lead once the target reaches both verified futures; the original first response is unchanged. The full-recording startup explicitly reserves a 32 MiB encoded aggregate including that response within the existing 64 MiB shared held budget; future bytes alone retain a 24 MiB cap, and non-startup playback keeps the SDK default. These are encoded reservoir limits, not total browser memory. Newly verified short peer pieces can refresh an older rate through a batch within one transfer and connection, retaining the 300 ms and 32 KiB floors, elapsed gaps and verification time. Origin bytes, duplicates and rejected responses cannot train this input; no first-byte timing sample or Rust/WASM binary change is introduced. The 27 October 330-second public pair on source 25354e3 and site acd26cd recorded 9 and 11 post-frame stalls, with fewer than 60 seconds observed after the wrap. That sustained-playback check remains failed; the estimator change requires fresh published-runtime qualification. Startup now has twelve seconds from the original first-fragment load entry, clipped to a shorter parent load deadline; ordinary speculative requests keep their eight-second expiry. Startup accepts parsed fragment start/duration roundoff within bounded machine precision, capped at one nanosecond, instead of falsely cancelling a matching context; sequence, continuity, level, key, size and duration checks remain authoritative. This does not establish stall-free or sustained 4K playback. A longer bounded wait does not establish successful real-source startup or alter required verified recovery headroom. Controlled correctness regressions do not establish reliable cold multi-viewer startup, decoded playback or traffic savings for this pin. When an owned source response finishes and its key is already known, eligible retained HAVE is published before FETCH withdrawal, including synchronous hls.js disposal; unknown keys do not delay playback for another hash. Cache/verification limits remain unchanged and no new peer-wait policy is enabled. This correction does not establish traffic savings or smoother playback. Peers exchange object-framing support in existing authenticated SDP offers and answers; an explicit version 2 is accepted only after current admitted SDP installation. Eligible new channels can therefore use verified range transfers before a periodic presence announcement; missing or unsupported values preserve conservative presence-derived behaviour. Admission, verification, upload limits and HTTP deadlines remain unchanged. Confirmed recorded main media requires a live same-key fetch lease before waiting for unavailable video; live and unknown playlists retain bounded seeding coordination. Sharing continues throughout active playback without an elapsed-time or cumulative-byte cutoff; upload rate, peers and cache remain bounded. Known pinned recordings use a client-generated bounded sliding live playlist with discontinuities across programme wraps and one visible player. The 267.32-second 4K programme preserves every original audio packet; a separately named, hash-pinned final fragment removes only 32 video frames after the soundtrack ends. The init and first 133 fragments remain byte-identical; the old immutable assets remain available. The next head can load before the tail ends; normal wraps do not end the element, reset its raw time or trigger replay priming. The bounded playlist retains 24 seconds of metadata behind the room clock so a slow initial response does not immediately eject the playhead; this does not enlarge the four-second media back buffer or encoded-media cache. A fixed per-session timeline origin maps raw media time to the shared clock; programme phase drives displayed time, telemetry and the musical pulse. Metadata preparation and peer creation remain after Play. Canonical manifest hashes and exact media URLs are checked, virtual global sequence/discontinuity values are signed against the unchanged piece catalogue, and a separate source/quality/epoch/manifest/duration cohort isolates this mode. Unsupported metadata and native HLS keep the ordinary VOD fallback; automatic clock corrections wait for sustained drift and stable, safely buffered playback, with the measured seek interruption added to the drift threshold, without changing music tempo. The responsive swarm picture keeps short labels and puts transfer rates and contribution statistics below it. A 16 KB score derived from the soundtrack drives a musical broadcast pulse against actual media time; pause, buffering, hidden pages and reduced motion stop it. This does not establish exact global audience counts or multi-speaker audio synchronisation. iPhone and iPad use the same peer-capable HLS path as other MediaSource-capable browsers; browser identity does not bypass sharing. The public Spry credential endpoint remains unconfigured pending an independently operated public endpoint. When configured, active playback requests and renews unique temporary TLS credentials from that independently operated instance, alongside STUN discovery. The supported public service uses its four-field credential contract and fresh one-hour leases, separately from KithMoot paired/private access. The final public instance endpoint remains operator configuration. This supplies a route for browsers that restrict direct UDP, including default Vanadium configurations. The bundle contains no relay password or operator root secret; availability diagnostics contain no credential. Pause cancels renewal. Issuer or route failure preserves HTTPS playback. Playback details can save or share a local JSON report with at most 240 one-second observations of actual frames, buffering, stalls and verified peer traffic, omitting network addresses, keys and credentials; no report is uploaded automatically. The HLS module prepares before Play without media requests or a player. The first tap attaches the selected media source and requests audible playback before awaiting room or peer setup; initial playback no longer waits for paused priming. This preserves request ordering but does not establish physical iPhone acceptance or stall-free startup. VOD fallback replay can still use a safely buffered current position while retaining buffered correction to the room. Reports retain raw media position/buffers and expose recording phase/duration separately; infinite continuous-media duration stays unavailable rather than being relabelled as the finite recording duration. Healthy network-stalled events with future data do not count as playback waits. The deployed 26 October 330-second same-M4 run used two fresh HTTP-cache-disabled Chrome profiles and the actual CDN assets, with no asset, controller or RTC overrides. Both had zero observed post-frame stalls/drops through the programme wrap and at least 60 seconds afterwards; accepted peer shares were 21.05% and 45.31%. First frames took 12.979 and 5.030 seconds. One midway report export per viewer remained in all measurements; A retained one nonfatal pre-frame aborted fragment event with no post-frame error increase. This is sampled same-host evidence, not physical-phone, independent-network, public TURN, wire-cost or eight-person-call acceptance. The earlier lab route passed public browser credential/CORS and hash-verified TLS data checks; that test route was retired. Fresh public-instance issuance, actual lease rotation during playback, independent-network cold-cache 4K and physical iPhone acceptance on the current revision remain separate gates. Positive peer waits require actual origin timing; a cold loader starts HTTP immediately while cached and late-HAVE peers retain their parallel race. Positive waits are bounded by the segment duration after measured origin recovery time; cached peer races start HTTP immediately and use an explicit peer-only Rust ranged planner with no internal HTTP source. The demo enables lateHaveRace: only native connections accepted at load entry can participate, after an actual exact-object HAVE arrives within the original 2.5-second window. HTTP continues immediately; one holder set is frozen and the deadline never extends. A verified calibration piece unlocks bounded pending work. Four-piece and 512 KiB request caps retain upload burst bounds for larger fragments. At the floor the peer arm cancels while its independent HTTP request continues. Normal buffered mixed transfers retain their HTTP ranges; older modules safely decline the unsupported mode. Range uploads copy the requested bytes across the WASM boundary, rather than the whole 4K object for every range. A separately packaged module Worker reuses the compiled Rust/WASM module for bounded piece scheduling and payload verification; HTTP continues during Worker startup or failure, and leaving the swarm terminates it. The bundle receipt pins the companion source and digest. This separates verification work from playback controls; measured device continuity and useful peer contribution remain acceptance checks. On native-HLS-capable browsers, repeated stalls can switch playback to native HLS; anonymous CORS is set before selecting the approved cross-origin media, peer resources close and native transfer totals are marked unavailable. Native recovery requests playback immediately and restores phase on metadata without a second Play; a later pause or policy rejection stays authoritative. Saved reports retain fixed HLS/native error codes, fallback reason and failed state without arbitrary messages or URLs. Terminal media failure restores Play again. A real Chrome recovery test decoded 333 native 4K frames with zero drops over 13 seconds after an intentional fatal Hls event; the transition interrupted playback for 3.827 seconds. This is recovery evidence, not sustained cold-cache or physical-phone acceptance. The Rust/WASM scheduler exchanges site-verified pieces of the unchanged 4K source, with HTTP completing the remainder, native controls, a Back to live action and shared-room invitation links. Integrity uses a site-pinned HTTPS digest catalogue with receiver-local commitment signing. Resource limits and reproduction: https://github.com/forgesworn/forgesworn.dev/blob/main/docs/media-showcase.md. The local runner compares native Sapflow and MediaMTX with the same H.264/AAC source and optionally real RelaySwarm delivery through Spry or coturn over UDP/TCP. Public process results are dated recordings; live origin CPU requires the local runner. Reproduction: https://github.com/forgesworn/forgesworn.dev/blob/main/docs/media-lab.md +- [4K listening room and comparison player](https://forgesworn.dev/media-lab.html): the complete licensed Deja Vu mix leads the homepage. Play & join starts or joins a shared listening clock and real RelaySwarm participation. For a new room, the first full-recording viewer prepares a bounded verified media reservoir locally before publishing the shared start time; preparation does not count as an active listener. A viewer still preparing a private start adopts a verified active room promptly, retires its empty old loader before the acknowledgement and preserves the original Play request; a failed acknowledgement restores an explicit retry. Cancelled or replaced asynchronous setup failures cannot fail a newer Play request; genuine current publication failures still restore retry. Existing rooms keep their advancing clocks and later listeners join live, the starter can leave while others continue, and the room expires after the last listener leaves a short grace period. Pause leaves; Play rejoins live. The recording loops while occupied; the 1080p excerpt has its own room. The live listener ticker includes joined listeners and excludes read-only page observers; Play/Pause events update it directly, with lease expiry for abrupt departures and unknown status during lost room observation. A confirmed empty room invites the first listener to start. One visible player per visitor, room participants distinct from locally connected peers, stable identity mapping through peerConnectionDetails(), proportional media-batch movement and rates, source-host feeds, explicitly self-reported remote links, separate loaded-source/verified-peer/upload counters and recent local peer contribution. Loaded source includes browser cache; playback details distinguish completed source response bodies from network and cache when timing coverage is available. Cache hits do not animate as fresh local network traffic; concealed timings remain unavailable. The browser integration pins RelaySwarm source c8120c5bf8c117e334a37a072b3bd6f3de46cc3a (package version 0.4.4), retaining bounded rolling startup planning, sustainable peer waits and range-sized WASM uploads. Startup preserves its verified contiguous future prefix before using the existing fourth residency slot even after the original first interval expires; that contiguous successor is not skipped by the previous fragment’s service-time lead once the target reaches both verified futures; the original first response is unchanged. The full-recording startup explicitly reserves a 32 MiB encoded aggregate including that response within the existing 64 MiB shared held budget; future bytes alone retain a 24 MiB cap, and non-startup playback keeps the SDK default. These are encoded reservoir limits, not total browser memory. Newly verified short peer pieces can refresh an older rate through a batch within one transfer and connection, retaining the 300 ms and 32 KiB floors, elapsed gaps and verification time. Origin bytes, duplicates and rejected responses cannot train this input; no first-byte timing sample or Rust/WASM binary change is introduced. The 27 October 330-second public pair on source 25354e3 and site acd26cd recorded 9 and 11 post-frame stalls, with fewer than 60 seconds observed after the wrap. That sustained-playback check remains failed; the estimator change requires fresh published-runtime qualification. Startup now has twelve seconds from the original first-fragment load entry, clipped to a shorter parent load deadline; ordinary speculative requests keep their eight-second expiry. Startup accepts parsed fragment start/duration roundoff within bounded machine precision, capped at one nanosecond, instead of falsely cancelling a matching context; sequence, continuity, level, key, size and duration checks remain authoritative. This does not establish stall-free or sustained 4K playback. A longer bounded wait does not establish successful real-source startup or alter required verified recovery headroom. Controlled correctness regressions do not establish reliable cold multi-viewer startup, decoded playback or traffic savings for this pin. When an owned source response finishes and its key is already known, eligible retained HAVE is published before FETCH withdrawal, including synchronous hls.js disposal; unknown keys do not delay playback for another hash. Cache/verification limits remain unchanged and no new peer-wait policy is enabled. This correction does not establish traffic savings or smoother playback. Peers exchange object-framing support in existing authenticated SDP offers and answers; an explicit version 2 is accepted only after current admitted SDP installation. Eligible new channels can therefore use verified range transfers before a periodic presence announcement; missing or unsupported values preserve conservative presence-derived behaviour. Admission, verification, upload limits and HTTP deadlines remain unchanged. Confirmed recorded main media requires a live same-key fetch lease before waiting for unavailable video; live and unknown playlists retain bounded seeding coordination. Sharing continues throughout active playback without an elapsed-time or cumulative-byte cutoff; upload rate, peers and cache remain bounded. Known pinned recordings use a client-generated bounded sliding live playlist with discontinuities across programme wraps and one visible player. The 267.32-second 4K programme preserves every original audio packet; a separately named, hash-pinned final fragment removes only 32 video frames after the soundtrack ends. The init and first 133 fragments remain byte-identical; the old immutable assets remain available. The next head can load before the tail ends; normal wraps do not end the element, reset its raw time or trigger replay priming. The bounded playlist retains 24 seconds of metadata behind the room clock so a slow initial response does not immediately eject the playhead; this does not enlarge the four-second media back buffer or encoded-media cache. A fixed per-session timeline origin maps raw media time to the shared clock; programme phase drives displayed time, telemetry and the musical pulse. Metadata preparation and peer creation remain after Play. Canonical manifest hashes and exact media URLs are checked, virtual global sequence/discontinuity values are signed against the unchanged piece catalogue, and a separate source/quality/epoch/manifest/duration cohort isolates this mode. Unsupported metadata and native HLS keep the ordinary VOD fallback; automatic clock corrections wait for sustained drift and stable, safely buffered playback, with the measured seek interruption added to the drift threshold, without changing music tempo. The responsive swarm picture keeps short labels and puts transfer rates and contribution statistics below it. A 16 KB score derived from the soundtrack drives a musical broadcast pulse against actual media time; pause, buffering, hidden pages and reduced motion stop it. This does not establish exact global audience counts or multi-speaker audio synchronisation. iPhone and iPad use the same peer-capable HLS path as other MediaSource-capable browsers; browser identity does not bypass sharing. The public Spry credential endpoint remains unconfigured pending an independently operated public endpoint. When configured, active playback requests and renews unique temporary TLS credentials from that independently operated instance, alongside STUN discovery. The supported public service uses its four-field credential contract and fresh one-hour leases, separately from KithMoot paired/private access. The final public instance endpoint remains operator configuration. This supplies a route for browsers that restrict direct UDP, including default Vanadium configurations. The bundle contains no relay password or operator root secret; availability diagnostics contain no credential. Pause cancels renewal. Issuer or route failure preserves HTTPS playback. Playback details can save or share a local JSON report with at most 240 one-second observations of actual frames, buffering, stalls and verified peer traffic, omitting network addresses, keys and credentials; no report is uploaded automatically. The HLS module prepares before Play without media requests or a player. The first tap attaches the selected media source and requests audible playback before awaiting room or peer setup; initial playback no longer waits for paused priming. This preserves request ordering but does not establish physical iPhone acceptance or stall-free startup. VOD fallback replay can still use a safely buffered current position while retaining buffered correction to the room. Reports retain raw media position/buffers and expose recording phase/duration separately; infinite continuous-media duration stays unavailable rather than being relabelled as the finite recording duration. Healthy network-stalled events with future data do not count as playback waits. The deployed 26 October 330-second same-M4 run used two fresh HTTP-cache-disabled Chrome profiles and the actual CDN assets, with no asset, controller or RTC overrides. Both had zero observed post-frame stalls/drops through the programme wrap and at least 60 seconds afterwards; accepted peer shares were 21.05% and 45.31%. First frames took 12.979 and 5.030 seconds. One midway report export per viewer remained in all measurements; A retained one nonfatal pre-frame aborted fragment event with no post-frame error increase. This is sampled same-host evidence, not physical-phone, independent-network, public TURN, wire-cost or eight-person-call acceptance. The earlier lab route passed public browser credential/CORS and hash-verified TLS data checks; that test route was retired. Fresh public-instance issuance, actual lease rotation during playback, independent-network cold-cache 4K and physical iPhone acceptance on the current revision remain separate gates. Positive peer waits require actual origin timing; a cold loader starts HTTP immediately while cached and late-HAVE peers retain their parallel race. Positive waits are bounded by the segment duration after measured origin recovery time; cached peer races start HTTP immediately and use an explicit peer-only Rust ranged planner with no internal HTTP source. The demo enables lateHaveRace: only native connections accepted at load entry can participate, after an actual exact-object HAVE arrives within the original 2.5-second window. HTTP continues immediately; one holder set is frozen and the deadline never extends. A verified calibration piece unlocks bounded pending work. Four-piece and 512 KiB request caps retain upload burst bounds for larger fragments. At the floor the peer arm cancels while its independent HTTP request continues. Normal buffered mixed transfers retain their HTTP ranges; older modules safely decline the unsupported mode. Range uploads copy the requested bytes across the WASM boundary, rather than the whole 4K object for every range. A separately packaged module Worker reuses the compiled Rust/WASM module for bounded piece scheduling and payload verification; HTTP continues during Worker startup or failure, and leaving the swarm terminates it. The bundle receipt pins the companion source and digest. This separates verification work from playback controls; measured device continuity and useful peer contribution remain acceptance checks. On native-HLS-capable browsers, repeated stalls can switch playback to native HLS; anonymous CORS is set before selecting the approved cross-origin media, peer resources close and native transfer totals are marked unavailable. Native recovery requests playback immediately and restores phase on metadata without a second Play; a later pause or policy rejection stays authoritative. Saved reports retain fixed HLS/native error codes, fallback reason and failed state without arbitrary messages or URLs. Terminal media failure restores Play again. A real Chrome recovery test decoded 333 native 4K frames with zero drops over 13 seconds after an intentional fatal Hls event; the transition interrupted playback for 3.827 seconds. This is recovery evidence, not sustained cold-cache or physical-phone acceptance. The Rust/WASM scheduler exchanges site-verified pieces of the unchanged 4K source, with HTTP completing the remainder, native controls, a Back to live action and shared-room invitation links. Integrity uses a site-pinned HTTPS digest catalogue with receiver-local commitment signing. Resource limits and reproduction: https://github.com/forgesworn/forgesworn.dev/blob/main/docs/media-showcase.md. The local runner compares native Sapflow and MediaMTX with the same H.264/AAC source and optionally real RelaySwarm delivery through Spry or coturn over UDP/TCP. Public process results are dated recordings; live origin CPU requires the local runner. Reproduction: https://github.com/forgesworn/forgesworn.dev/blob/main/docs/media-lab.md - [Deployed 4K playback evidence](https://github.com/forgesworn/forgesworn.dev/blob/main/docs/evidence/public-prepared-adoption-4k-20261026.json): dated 26 October 2026; two fresh Chrome profiles on one M4 Max, actual public assets, 330 seconds each, zero observed post-frame stalls/drops, 21.05% / 45.31% accepted peer media. Startup took 12.979 / 5.030 seconds. Includes report-export interactions and one retained pre-frame abort; no physical-phone, public TURN, independent-network or competitor advantage claim. +- [Peer model diagnostics](https://github.com/forgesworn/forgesworn.dev/blob/main/docs/media-showcase.md): normal saved playback reports project fixed short-flow batch counts/bytes/latest span, model-evaluation decisions and numeric inputs, plus the latest candidate from an attempt rejected before transfer creation. Missing measurements remain null. Evaluation counts are not requests, verified pieces are not playback credit, and these receipts do not establish throughput or savings. No identifiers, raw SDK records, new requests, timers or selection policy are added. - [28 October public verified-piece-flow check](https://github.com/forgesworn/forgesworn.dev/blob/main/docs/evidence/public-verified-piece-flow-20261028.json): RelaySwarm d4a1235/site 46f7142, two fresh headless Chrome profiles on one M4 using controlled signalling and actual public assets without source overrides. Overall RED solely because the recorded wall span 329,993 ms was below the strict 330,000 ms gate; monotonic 330,002.347833 ms does not replace it or rescore the run. Both viewers recorded zero post-frame stalls/player errors/dropped frames and 71.665 seconds after a programme wrap; first frames 3511.2/9346.5 ms. Accepted peer 253,697,256/74,560,956 B (23.331%/6.932% of accepted peer plus loaded-source bytes) is not HTTP/wire savings. Linked evidence includes complete HTTP body accounting with partial/cancelled bodies and 44/41 SDK ring evictions, leaving early rich SDK/Hls detail unknown. No physical-phone, NAT/public TURN, synchronisation, competitor or causal performance qualification; prior results remain unchanged. - [Failed public pair startup attempt](https://github.com/forgesworn/forgesworn.dev/blob/main/docs/evidence/public-pair-startup-red-20261027.json): 27 October 2026, source cce9807/e910147. Viewer A presented 4K after 4.629 seconds; viewer B reached its one-shot startup deadline without a frame. The planned observation did not complete and this is not a 90-second or 330-second pass. Current terminal startup handling restores an explicit Play retry instead of retrying a permanently failed barrier; it does not resolve the underlying startup deadline or extend the deadline. Saved target/coverage/headroom values describe the last observed diagnostic geometry, not present residency after failure. - [Short public pair diagnostic](https://github.com/forgesworn/forgesworn.dev/blob/main/docs/evidence/public-pair-startup-diagnostic-20261027.json): 27 October 2026, site 03c9c95 and RelaySwarm e910147. Two fresh Chrome profiles with HTTP caching disabled on one M4 completed 90.2 seconds after the second first frame. Accepted peer video was 6.19 MB / 159.19 MB (1.74% / 47.26% of source-plus-peer loaded video), with zero reported post-frame stalls/errors and eight post-frame dropped frames in the second viewer. The second viewer still recorded 309.77 MB of HTTP bodies, including partial/aborted responses, so accepted peer share does not establish equivalent source-traffic savings. This shows useful participation; clean-frame, full-loop, phone, separate-network, public TURN, wire savings and competitor qualifications remain open. The earlier failed join remains published; this result does not establish a streaming-performance improvement from the UI patch. diff --git a/site/media-lab.html b/site/media-lab.html index bab8bd9..5c1f931 100644 --- a/site/media-lab.html +++ b/site/media-lab.html @@ -123,6 +123,6 @@ - + diff --git a/site/media-lab.mjs b/site/media-lab.mjs index 1a0e174..73e83ef 100644 --- a/site/media-lab.mjs +++ b/site/media-lab.mjs @@ -2,7 +2,7 @@ import { readInitialLiveStart } from './media-live-start.mjs'; import { createSourceResponseStats, publicSourceResource, transferBytes } from './media-transfer-stats.mjs?v=20261027-visual-provenance'; import { createNativePlaybackFallback } from './media-playback-fallback.mjs?v=20261025-prepared-room'; import { createPlaybackPrime } from './media-playback-prime.mjs?v=20261025-prepared-room'; -import { createPlaybackReport, projectStartupBuffer } from './media-playback-report.mjs?v=20261027-startup-terminal'; +import { createPlaybackReport, projectStartupBuffer } from './media-playback-report.mjs?v=20261028-peer-fit-models'; const DASH = '—'; export const observed = (value) => typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : null; @@ -424,7 +424,7 @@ async function initialise() { publicRoom?.stop(); publicRoom = null; const pending = (async () => { const [{ createListenerSession }, { PUBLIC_SWARM_SOURCE_SHA256, PUBLIC_SWARM_RELAYS }] = await Promise.all([ - import('./media-listener-session.mjs?v=20261028-verified-piece-flow'), import('./media-public-swarm.mjs?v=20261028-verified-piece-flow'), + import('./media-listener-session.mjs?v=20261028-peer-fit-models'), import('./media-public-swarm.mjs?v=20261028-peer-fit-models'), ]); if (request !== publicRoomRequest || pageAbort.signal.aborted) return null; const clock = createListenerSession({ room: `forgesworn-dejavu-listening-v${quality === 'full' ? 2 : 1}-${quality}`, source: PUBLIC_SWARM_SOURCE_SHA256, @@ -1522,7 +1522,7 @@ async function initialise() { if (player) { let peer, setupEpoch; try { - const { createPublicSwarm, prepareRecordedSource, createRecordedLive } = await import('./media-public-swarm.mjs?v=20261028-verified-piece-flow'); + const { createPublicSwarm, prepareRecordedSource, createRecordedLive } = await import('./media-public-swarm.mjs?v=20261028-peer-fit-models'); if (!owns() || s.hls !== player) return; // These two exports share the exact helper module/recording brand. // A cold first room prepares locally before publishing its clock. diff --git a/site/media-listener-session.mjs b/site/media-listener-session.mjs index 0ea732f..a2c9c62 100644 --- a/site/media-listener-session.mjs +++ b/site/media-listener-session.mjs @@ -1,7 +1,7 @@ // Signed, short-lived observations of a shared listening clock. This is an // experimental public addressable event (NIP-01), not NIP-78 private app storage. // Relay partitions and dishonest clients prevent an authoritative audience count. -import { finalizeEvent, generateSecretKey, verifyEvent } from './vendor/media-peer-demo.js?v=20261028-verified-piece-flow'; +import { finalizeEvent, generateSecretKey, verifyEvent } from './vendor/media-peer-demo.js?v=20261028-peer-fit-models'; export const LISTENER_SESSION_KIND = 30378; export const LISTENER_TELEMETRY_KIND = 20378; diff --git a/site/media-playback-report.mjs b/site/media-playback-report.mjs index 0cdc87f..5b9782f 100644 --- a/site/media-playback-report.mjs +++ b/site/media-playback-report.mjs @@ -118,6 +118,40 @@ function connections(input) { })); } +function peerFlowModel(input) { + if (!object(input)) return null; + return { + decision: choice(value(input, 'decision'), ['fit', 'useful-unknown', 'refresh', 'cooldown-blocked', 'known-slow']), + availableMs: number(value(input, 'availableMs')), pieceSize: positiveInteger(value(input, 'pieceSize')), + firstByteMs: number(value(input, 'firstByteMs')), rateBytesPerSecond: number(value(input, 'rateBytesPerSecond')), + probeAgeMs: number(value(input, 'probeAgeMs')), usefulAgeMs: number(value(input, 'usefulAgeMs')), + }; +} + +function peerFlowDiagnostics(input) { + if (!object(input)) return null; + const core = value(input, 'core'); if (!object(core)) return null; + const multi = value(core, 'multiHolder'); if (!object(multi)) return null; + const flow = value(multi, 'peerFlow'); if (!object(flow)) return null; + const batch = value(flow, 'lastVerifiedShortBatch'), evaluations = value(flow, 'modelEvaluations'); + const noModel = value(flow, 'lastNoModel'); + // Fixed scalar projection only: evaluations are not requests or playback + // credit, and the latest model is not a record of every candidate. + return { + verifiedShortBatches: integer(value(flow, 'verifiedShortBatches')), + verifiedShortBytes: integer(value(flow, 'verifiedShortBytes')), + lastVerifiedShortBatch: object(batch) ? { bytes: positiveInteger(value(batch, 'bytes')), spanMs: number(value(batch, 'spanMs')) } : null, + modelEvaluations: object(evaluations) ? { + fit: integer(value(evaluations, 'fit')), 'useful-unknown': integer(value(evaluations, 'useful-unknown')), + refresh: integer(value(evaluations, 'refresh')), 'cooldown-blocked': integer(value(evaluations, 'cooldown-blocked')), + 'known-slow': integer(value(evaluations, 'known-slow')), + } : null, + lastModel: peerFlowModel(value(flow, 'lastModel')), noModelTransfers: integer(value(flow, 'noModelTransfers')), + lastNoModel: object(noModel) ? { candidateCount: integer(value(noModel, 'candidateCount')), + model: peerFlowModel(value(noModel, 'model')) } : null, + }; +} + function peerAttemptDiagnostics(input) { if (!object(input)) return null; const count = (...path) => { @@ -202,6 +236,7 @@ function sample(input, elapsedMs) { sourceTimingCoverage, peerEnabled: boolean(value(input, 'peerEnabled')), connectedPeers: integer(value(input, 'connectedPeers')), peerAttemptDiagnostics: peerAttemptDiagnostics(value(input, 'peerAttemptDiagnostics')), + peerFlowDiagnostics: peerFlowDiagnostics(value(input, 'peerAttemptDiagnostics')), transferWorkerState: choice(value(input, 'transferWorkerState'), ['off', 'waiting-core', 'loading', 'ready', 'failed', 'stopped']), roomPrepared: boolean(value(input, 'roomPrepared')), roomReady: boolean(value(input, 'roomReady')), roomListeners: integer(value(input, 'roomListeners')), connections: connections(value(input, 'connections')), diff --git a/site/media-public-swarm.mjs b/site/media-public-swarm.mjs index 0e7a15c..f0d25a3 100644 --- a/site/media-public-swarm.mjs +++ b/site/media-public-swarm.mjs @@ -3,7 +3,7 @@ // A receiver's ephemeral key wraps that digest for the existing live-commitment // verifier; this is local attestation, not a live broadcaster signing service. import { createHlsSwarm, commitmentContent, commitmentPieceSize, segmentMediaContext, KIND_SEGMENT_COMMITMENT, finalizeEvent, - generateSecretKey, relayswarmBuild } from './vendor/media-peer-demo.js?v=20261028-verified-piece-flow'; + generateSecretKey, relayswarmBuild } from './vendor/media-peer-demo.js?v=20261028-peer-fit-models'; import { observeOriginLoader } from './media-transfer-stats.mjs?v=20261027-visual-provenance'; import { createPublicTurnCredentials } from './media-turn-credentials.mjs?v=20261025-prepared-room'; import { parseRecordedManifest, createRecordedLive } from './media-recorded-live.mjs?v=20261025-prepared-room'; @@ -479,7 +479,7 @@ export function createPublicSwarm({ Hls, hls, video, playlistUrl, quality, signa swarm = createSwarm({ mode: 'peer-first', swarmId: plan.swarmId, relays: [...PUBLIC_SWARM_RELAYS], streamEvent, getCommitment, serve: true, serveOnCellular: false, coreWasm: new URL('./vendor/relayswarm-core.wasm?v=20261026-prepared-adoption', import.meta.url), multiHolder: true, - transferWorkerUrl: new URL('./vendor/relayswarm-transfer-worker.js?v=20261028-verified-piece-flow', import.meta.url), + transferWorkerUrl: new URL('./vendor/relayswarm-transfer-worker.js?v=20261028-peer-fit-models', import.meta.url), zeroBudgetPeerRace: true, lateHaveRace: true, sustainablePeerWait: true, warmAhead: false, startupBufferMaxBytes: (needsStartupBuffer ? 32 : 24) * 1024 * 1024, diff --git a/site/template.html b/site/template.html index 59ba6fd..72f4e3e 100644 --- a/site/template.html +++ b/site/template.html @@ -1985,6 +1985,6 @@

Pick a block and start

}); }); - + diff --git a/site/vendor/media-peer-demo.NOTICE.txt b/site/vendor/media-peer-demo.NOTICE.txt index 26eb0f4..32779c1 100644 --- a/site/vendor/media-peer-demo.NOTICE.txt +++ b/site/vendor/media-peer-demo.NOTICE.txt @@ -1,5 +1,5 @@ RelaySwarm 0.4.4 -https://github.com/forgesworn/relayswarm/tree/d4a1235b035b4244ea73b55b1da0d4f88f64c376 +https://github.com/forgesworn/relayswarm/tree/c8120c5bf8c117e334a37a072b3bd6f3de46cc3a MIT License diff --git a/site/vendor/media-peer-demo.build.json b/site/vendor/media-peer-demo.build.json index c5a6f7a..3b5dc5a 100644 --- a/site/vendor/media-peer-demo.build.json +++ b/site/vendor/media-peer-demo.build.json @@ -1,17 +1,17 @@ { "schema": 1, "project": "https://github.com/forgesworn/relayswarm", - "sourceCommit": "d4a1235b035b4244ea73b55b1da0d4f88f64c376", + "sourceCommit": "c8120c5bf8c117e334a37a072b3bd6f3de46cc3a", "version": "0.4.4", - "sourceArchiveSha256": "441c3482cb43b0b250f439f40bb5457a8aa887e354acb4be8cedb0eb76aa385f", + "sourceArchiveSha256": "c665848cc6d3ec7aa99448dd28cf6cf333e13393f48fc7f5c82ddd31ddc007e2", "packageLockSha256": "18a91b8d697ebcab1d259d4de876167dcbd4d47fc3c82196d179c4c490adca4a", "bundle": "media-peer-demo.js", - "bundleSha256": "0678f84ada02ac7ec5d5585363670bdc77730af99c7488b61c61a1512c8a9dc5", - "bundleBytes": 263683, + "bundleSha256": "f9b89c02700b1f82da81eb855bd79d4c7459d02e720a639860c8c38abc723800", + "bundleBytes": 265067, "transferWorker": { "file": "relayswarm-transfer-worker.js", "bytes": 7074, - "sha256": "e1e02f93345f28cdbf96f1a20593e1f65d7b115a7ee1dd0ced1f0ee4b81164ba", + "sha256": "030c8137f5a9bcbca2bf9dde6c3cde64e00262bfc6a9c190f3aa097011f8d7e4", "source": "src/browser/core-transfer-worker-runtime.mjs" }, "sourceMap": false, diff --git a/site/vendor/media-peer-demo.js b/site/vendor/media-peer-demo.js index 3ea4b8a..41d324c 100644 --- a/site/vendor/media-peer-demo.js +++ b/site/vendor/media-peer-demo.js @@ -1,7 +1,7 @@ -/*! RelaySwarm 0.4.4; public source d4a1235b035b4244ea73b55b1da0d4f88f64c376. See media-peer-demo.NOTICE.txt. */ -function ns(n,e){try{let t=a=>{if(!n)return null;let l=typeof n.getResponseHeader=="function"?n.getResponseHeader(a):n.headers?.get?.(a);return typeof l=="string"?l:null},r=t("Date"),s=typeof r=="string"&&/\sGMT$/u.test(r.trim())?Date.parse(r):NaN;if(!Number.isFinite(s))return null;let i=Number(t("Age")),o=s+(Number.isFinite(i)&&i>0?i*1e3:0)-e;return Number.isFinite(o)&&Math.abs(o)<=6048e5?o:null}catch{return null}}function ss(n){return{samples:n.length,offsetSeconds:n.length?Math.round(Math.max(...n)/1e3):null}}function Ft(n){return n instanceof Uint8Array||ArrayBuffer.isView(n)&&n.constructor.name==="Uint8Array"}function Ne(n,e=""){if(!Number.isSafeInteger(n)||n<0){let t=e&&`"${e}" `;throw new Error(`${t}expected integer >= 0, got ${n}`)}}function ae(n,e,t=""){let r=Ft(n),s=n?.length,i=e!==void 0;if(!r||i&&s!==e){let o=t&&`"${t}" `,a=i?` of length ${e}`:"",l=r?`length=${s}`:`type=${typeof n}`;throw new Error(o+"expected Uint8Array"+a+", got "+l)}return n}function pt(n){if(typeof n!="function"||typeof n.create!="function")throw new Error("Hash must wrapped by utils.createHasher");Ne(n.outputLen),Ne(n.blockLen)}function At(n,e=!0){if(n.destroyed)throw new Error("Hash instance has been destroyed");if(e&&n.finished)throw new Error("Hash#digest() has already been called")}function os(n,e){ae(n,void 0,"digestInto() output");let t=e.outputLen;if(n.length='+t)}function Ge(...n){for(let e=0;e>>e}var as=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",lo=Array.from({length:256},(n,e)=>e.toString(16).padStart(2,"0"));function Pe(n){if(ae(n),as)return n.toHex();let e="";for(let t=0;t=$e._0&&n<=$e._9)return n-$e._0;if(n>=$e.A&&n<=$e.F)return n-($e.A-10);if(n>=$e.a&&n<=$e.f)return n-($e.a-10)}function Te(n){if(typeof n!="string")throw new Error("hex string expected, got "+typeof n);if(as)return Uint8Array.fromHex(n);let e=n.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let r=new Uint8Array(t);for(let s=0,i=0;sn(i).update(s).digest(),r=n(void 0);return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=s=>n(s),Object.assign(t,e),Object.freeze(t)}function Ye(n=32){let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(n))}var cs=n=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,n])});function hs(n,e,t){return n&e^~n&t}function us(n,e,t){return n&e^n&t^e&t}var ar=class{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,r,s){this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=s,this.buffer=new Uint8Array(e),this.view=or(this.buffer)}update(e){At(this),ae(e);let{view:t,buffer:r,blockLen:s}=this,i=e.length;for(let o=0;os-o&&(this.process(r,0),o=0);for(let d=o;du.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d>>3,m=De(g,17)^De(g,19)^g>>>10;rt[d]=m+rt[d-7]+f+rt[d-16]|0}let{A:r,B:s,C:i,D:o,E:a,F:l,G:c,H:u}=this;for(let d=0;d<64;d++){let p=De(a,6)^De(a,11)^De(a,25),g=u+p+hs(a,l,c)+co[d]+rt[d]|0,m=(De(r,2)^De(r,13)^De(r,22))+us(r,s,i)|0;u=c,c=l,l=a,a=o+g|0,o=i,i=s,s=r,r=g+m|0}r=r+this.A|0,s=s+this.B|0,i=i+this.C|0,o=o+this.D|0,a=a+this.E|0,l=l+this.F|0,c=c+this.G|0,u=u+this.H|0,this.set(r,s,i,o,a,l,c,u)}roundClean(){Ge(rt)}destroy(){this.set(0,0,0,0,0,0,0,0),Ge(this.buffer)}},Qr=class extends Jr{A=Ze[0]|0;B=Ze[1]|0;C=Ze[2]|0;D=Ze[3]|0;E=Ze[4]|0;F=Ze[5]|0;G=Ze[6]|0;H=Ze[7]|0;constructor(){super(32)}};var Fe=ls(()=>new Qr,cs(1));var tn=BigInt(0),en=BigInt(1);function qt(n,e=""){if(typeof n!="boolean"){let t=e&&`"${e}" `;throw new Error(t+"expected boolean, got type="+typeof n)}return n}function ds(n){if(typeof n=="bigint"){if(!lr(n))throw new Error("positive bigint expected, got "+n)}else Ne(n);return n}function jt(n){let e=ds(n).toString(16);return e.length&1?"0"+e:e}function fs(n){if(typeof n!="string")throw new Error("hex string expected, got "+typeof n);return n===""?tn:BigInt("0x"+n)}function nt(n){return fs(Pe(n))}function rn(n){return fs(Pe(ho(ae(n)).reverse()))}function cr(n,e){Ne(e),n=ds(n);let t=Te(n.toString(16).padStart(e*2,"0"));if(t.length!==e)throw new Error("number too large");return t}function nn(n,e){return cr(n,e).reverse()}function ho(n){return Uint8Array.from(n)}function ps(n){return Uint8Array.from(n,(e,t)=>{let r=e.charCodeAt(0);if(e.length!==1||r>127)throw new Error(`string contains non-ASCII character "${n[t]}" with code ${r} at position ${t}`);return r})}var lr=n=>typeof n=="bigint"&&tn<=n;function uo(n,e,t){return lr(n)&&lr(e)&&lr(t)&&e<=n&&ntn;n>>=en,e+=1);return e}var Wt=n=>(en<new Uint8Array(b),s=Uint8Array.of(),i=Uint8Array.of(0),o=Uint8Array.of(1),a=1e3,l=r(n),c=r(n),u=0,d=()=>{l.fill(1),c.fill(0),u=0},p=(...b)=>t(c,be(l,...b)),g=(b=s)=>{c=p(i,b),l=p(),b.length!==0&&(c=p(o,b),l=p())},f=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let b=0,v=[];for(;b{d(),g(b);let w;for(;!(w=v(f()));)g();return d(),w}}function Kt(n,e={},t={}){if(!n||typeof n!="object")throw new Error("expected valid options object");function r(i,o,a){let l=n[i];if(a&&l===void 0)return;let c=typeof l;if(c!==o||l===null)throw new Error(`param "${i}" is invalid: expected ${o}, got ${c}`)}let s=(i,o)=>Object.entries(i).forEach(([a,l])=>r(a,l,o));s(e,!1),s(t,!0)}function on(n){let e=new WeakMap;return(t,...r)=>{let s=e.get(t);if(s!==void 0)return s;let i=n(t,...r);return e.set(t,i),i}}var Me=BigInt(0),Ae=BigInt(1),gt=BigInt(2),ws=BigInt(3),vs=BigInt(4),xs=BigInt(5),fo=BigInt(7),Ss=BigInt(8),po=BigInt(9),Es=BigInt(16);function Ue(n,e){let t=n%e;return t>=Me?t:e+t}function _e(n,e,t){let r=n;for(;e-- >Me;)r*=r,r%=t;return r}function ys(n,e){if(n===Me)throw new Error("invert: expected non-zero number");if(e<=Me)throw new Error("invert: expected positive modulus, got "+e);let t=Ue(n,e),r=e,s=Me,i=Ae,o=Ae,a=Me;for(;t!==Me;){let c=r/t,u=r%t,d=s-o*c,p=i-a*c;r=t,t=u,s=o,i=a,o=d,a=p}if(r!==Ae)throw new Error("invert: does not exist");return Ue(s,e)}function ln(n,e,t){if(!n.eql(n.sqr(e),t))throw new Error("Cannot find square root")}function As(n,e){let t=(n.ORDER+Ae)/vs,r=n.pow(e,t);return ln(n,r,e),r}function go(n,e){let t=(n.ORDER-xs)/Ss,r=n.mul(e,gt),s=n.pow(r,t),i=n.mul(e,s),o=n.mul(n.mul(i,gt),s),a=n.mul(i,n.sub(o,n.ONE));return ln(n,a,e),a}function mo(n){let e=kt(n),t=ks(n),r=t(e,e.neg(e.ONE)),s=t(e,r),i=t(e,e.neg(r)),o=(n+fo)/Es;return(a,l)=>{let c=a.pow(l,o),u=a.mul(c,r),d=a.mul(c,s),p=a.mul(c,i),g=a.eql(a.sqr(u),l),f=a.eql(a.sqr(d),l);c=a.cmov(c,u,g),u=a.cmov(p,d,f);let m=a.eql(a.sqr(u),l),b=a.cmov(c,u,m);return ln(a,b,l),b}}function ks(n){if(n1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return As;let i=s.pow(r,e),o=(e+Ae)/gt;return function(l,c){if(l.is0(c))return c;if(bs(l,c)!==1)throw new Error("Cannot find square root");let u=t,d=l.mul(l.ONE,i),p=l.pow(c,e),g=l.pow(c,o);for(;!l.eql(p,l.ONE);){if(l.is0(p))return l.ZERO;let f=1,m=l.sqr(p);for(;!l.eql(m,l.ONE);)if(f++,m=l.sqr(m),f===u)throw new Error("Cannot find square root");let b=Ae<(r[s]="function",r),e);return Kt(n,t),n}function wo(n,e,t){if(tMe;)t&Ae&&(r=n.mul(r,s)),s=n.sqr(s),t>>=Ae;return r}function hr(n,e,t=!1){let r=new Array(e.length).fill(t?n.ZERO:void 0),s=e.reduce((o,a,l)=>n.is0(a)?o:(r[l]=o,n.mul(o,a)),n.ONE),i=n.inv(s);return e.reduceRight((o,a,l)=>n.is0(a)?o:(r[l]=n.mul(o,r[l]),n.mul(o,a)),i),r}function bs(n,e){let t=(n.ORDER-Ae)/gt,r=n.pow(e,t),s=n.eql(r,n.ONE),i=n.eql(r,n.ZERO),o=n.eql(r,n.neg(n.ONE));if(!s&&!i&&!o)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function vo(n,e){e!==void 0&&Ne(e);let t=e!==void 0?e:n.toString(2).length,r=Math.ceil(t/8);return{nBitLength:t,nByteLength:r}}var an=class{ORDER;BITS;BYTES;isLE;ZERO=Me;ONE=Ae;_lengths;_sqrt;_mod;constructor(e,t={}){if(e<=Me)throw new Error("invalid field: expected ORDER > 0, got "+e);let r;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(r=t.BITS),typeof t.sqrt=="function"&&(this.sqrt=t.sqrt),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=t.allowedLengths?.slice()),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:s,nByteLength:i}=vo(e,r);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=s,this.BYTES=i,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return Ue(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return Me<=e&&es)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);let c=new Uint8Array(s);c.set(e,i?0:c.length-e.length),e=c}if(e.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+e.length);let l=i?rn(e):nt(e);if(a&&(l=Ue(l,o)),!t&&!this.isValid(l))throw new Error("invalid field element: outside of range 0..ORDER");return l}invertBatch(e){return hr(this,e)}cmov(e,t,r){return r?t:e}};function kt(n,e={}){return new an(n,e)}function Ms(n){if(typeof n!="bigint")throw new Error("field order must be bigint");let e=n.toString(2).length;return Math.ceil(e/8)}function hn(n){let e=Ms(n);return e+Math.ceil(e/2)}function ur(n,e,t=!1){ae(n);let r=n.length,s=Ms(e),i=hn(e);if(r<16||r1024)throw new Error("expected "+i+"-1024 bytes of input, got "+r);let o=t?rn(n):nt(n),a=Ue(o,e-Ae)+Ae;return t?nn(a,s):cr(a,s)}var Mt=BigInt(0),mt=BigInt(1);function Vt(n,e){let t=e.negate();return n?t:e}function pn(n,e){let t=hr(n.Fp,e.map(r=>r.Z));return e.map((r,s)=>n.fromAffine(r.toAffine(t[s])))}function Ls(n,e){if(!Number.isSafeInteger(n)||n<=0||n>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+n)}function un(n,e){Ls(n,e);let t=Math.ceil(e/n)+1,r=2**(n-1),s=2**n,i=Wt(n),o=BigInt(n);return{windows:t,windowSize:r,mask:i,maxNumber:s,shiftBy:o}}function Bs(n,e,t){let{windowSize:r,mask:s,maxNumber:i,shiftBy:o}=t,a=Number(n&s),l=n>>o;a>r&&(a-=i,l+=mt);let c=e*r,u=c+Math.abs(a)-1,d=a===0,p=a<0,g=e%2!==0;return{nextN:l,offset:u,isZero:d,isNeg:p,isNegF:g,offsetF:c}}var dn=new WeakMap,_s=new WeakMap;function fn(n){return _s.get(n)||1}function Rs(n){if(n!==Mt)throw new Error("invalid wNAF")}var dr=class{BASE;ZERO;Fn;bits;constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,r=this.ZERO){let s=e;for(;t>Mt;)t&mt&&(r=r.add(s)),s=s.double(),t>>=mt;return r}precomputeWindow(e,t){let{windows:r,windowSize:s}=un(t,this.bits),i=[],o=e,a=o;for(let l=0;lMt||r>Mt;)t&mt&&(i=i.add(s)),r&mt&&(o=o.add(s)),s=s.double(),t>>=mt,r>>=mt;return{p1:i,p2:o}}function Ts(n,e,t){if(e){if(e.ORDER!==n)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return cn(e),e}else return kt(n,{isLE:t})}function Is(n,e,t={},r){if(r===void 0&&(r=n==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${n} CURVE object`);for(let l of["p","n","h"]){let c=e[l];if(!(typeof c=="bigint"&&c>Mt))throw new Error(`CURVE.${l} must be positive bigint`)}let s=Ts(e.p,t.Fp,r),i=Ts(e.n,t.Fn,r),a=["Gx","Gy","a",n==="weierstrass"?"b":"d"];for(let l of a)if(!s.isValid(e[l]))throw new Error(`CURVE.${l} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:s,Fn:i}}function fr(n,e){return function(r){let s=n(r);return{secretKey:s,publicKey:e(s)}}}var pr=class{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,t){if(pt(e),ae(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let r=this.blockLen,s=new Uint8Array(r);s.set(t.length>r?e.create().update(t).digest():t);for(let i=0;inew pr(n,e).update(t).digest();st.create=(n,e)=>new pr(n,e);var Cs=(n,e)=>(n+(n>=0?e:-e)/Ns)/e;function xo(n,e,t){let[[r,s],[i,o]]=e,a=Cs(o*n,t),l=Cs(-s*n,t),c=n-a*r-l*i,u=-a*s-l*o,d=c=g||u=g)throw new Error("splitScalar (endomorphism): failed, k="+n);return{k1neg:d,k1:c,k2neg:p,k2:u}}function mn(n){if(!["compact","recovered","der"].includes(n))throw new Error('Signature format must be "compact", "recovered", or "der"');return n}function gn(n,e){let t={};for(let r of Object.keys(e))t[r]=n[r]===void 0?e[r]:n[r];return qt(t.lowS,"lowS"),qt(t.prehash,"prehash"),t.format!==void 0&&mn(t.format),t}var yn=class extends Error{constructor(e=""){super(e)}},it={Err:yn,_tlv:{encode:(n,e)=>{let{Err:t}=it;if(n<0||n>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");let r=e.length/2,s=jt(r);if(s.length/2&128)throw new t("tlv.encode: long form length too big");let i=r>127?jt(s.length/2|128):"";return jt(n)+i+s+e},decode(n,e){let{Err:t}=it,r=0;if(n<0||n>256)throw new t("tlv.encode: wrong tag");if(e.length<2||e[r++]!==n)throw new t("tlv.decode: wrong tlv");let s=e[r++],i=!!(s&128),o=0;if(!i)o=s;else{let l=s&127;if(!l)throw new t("tlv.decode(long): indefinite length not supported");if(l>4)throw new t("tlv.decode(long): byte length is too big");let c=e.subarray(r,r+l);if(c.length!==l)throw new t("tlv.decode: length bytes not complete");if(c[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let u of c)o=o<<8|u;if(r+=l,o<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(r,r+o);if(a.length!==o)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(r+o)}}},_int:{encode(n){let{Err:e}=it;if(n{let{X:x,Y:S,Z:M}=N;if(r.eql(M,r.ONE))return{x,y:S};let H=N.is0();h==null&&(h=H?r.ONE:r.inv(M));let D=r.mul(x,h),B=r.mul(S,h),U=r.mul(M,h);if(H)return{x:r.ZERO,y:r.ZERO};if(!r.eql(U,r.ONE))throw new Error("invZ was invalid");return{x:D,y:B}}),k=on(N=>{if(N.is0()){if(e.allowInfinityPoint&&!r.is0(N.Y))return;throw new Error("bad point: ZERO")}let{x:h,y:x}=N.toAffine();if(!r.isValid(h)||!r.isValid(x))throw new Error("bad point: x or y not field elements");if(!b(h,x))throw new Error("bad point: equation left != right");if(!N.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function W(N,h,x,S,M){return x=new _(r.mul(x.X,N),x.Y,x.Z),h=Vt(S,h),x=Vt(M,x),h.add(x)}class _{static BASE=new _(i.Gx,i.Gy,r.ONE);static ZERO=new _(r.ZERO,r.ONE,r.ZERO);static Fp=r;static Fn=s;X;Y;Z;constructor(h,x,S){this.X=T("x",h),this.Y=T("y",x,!0),this.Z=T("z",S),Object.freeze(this)}static CURVE(){return i}static fromAffine(h){let{x,y:S}=h||{};if(!h||!r.isValid(x)||!r.isValid(S))throw new Error("invalid affine point");if(h instanceof _)throw new Error("projective point not allowed");return r.is0(x)&&r.is0(S)?_.ZERO:new _(x,S,r.ONE)}static fromBytes(h){let x=_.fromAffine(f(ae(h,void 0,"point")));return x.assertValidity(),x}static fromHex(h){return _.fromBytes(Te(h))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(h=8,x=!0){return P.createCache(this,h),x||this.multiply(gr),this}assertValidity(){k(this)}hasEvenY(){let{y:h}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(h)}equals(h){O(h);let{X:x,Y:S,Z:M}=this,{X:H,Y:D,Z:B}=h,U=r.eql(r.mul(x,B),r.mul(H,M)),C=r.eql(r.mul(S,B),r.mul(D,M));return U&&C}negate(){return new _(this.X,r.neg(this.Y),this.Z)}double(){let{a:h,b:x}=i,S=r.mul(x,gr),{X:M,Y:H,Z:D}=this,B=r.ZERO,U=r.ZERO,C=r.ZERO,z=r.mul(M,M),ee=r.mul(H,H),te=r.mul(D,D),$=r.mul(M,H);return $=r.add($,$),C=r.mul(M,D),C=r.add(C,C),B=r.mul(h,C),U=r.mul(S,te),U=r.add(B,U),B=r.sub(ee,U),U=r.add(ee,U),U=r.mul(B,U),B=r.mul($,B),C=r.mul(S,C),te=r.mul(h,te),$=r.sub(z,te),$=r.mul(h,$),$=r.add($,C),C=r.add(z,z),z=r.add(C,z),z=r.add(z,te),z=r.mul(z,$),U=r.add(U,z),te=r.mul(H,D),te=r.add(te,te),z=r.mul(te,$),B=r.sub(B,z),C=r.mul(te,ee),C=r.add(C,C),C=r.add(C,C),new _(B,U,C)}add(h){O(h);let{X:x,Y:S,Z:M}=this,{X:H,Y:D,Z:B}=h,U=r.ZERO,C=r.ZERO,z=r.ZERO,ee=i.a,te=r.mul(i.b,gr),$=r.mul(x,H),ne=r.mul(S,D),ue=r.mul(M,B),Z=r.add(x,S),oe=r.add(H,D);Z=r.mul(Z,oe),oe=r.add($,ne),Z=r.sub(Z,oe),oe=r.add(x,M);let ge=r.add(H,B);return oe=r.mul(oe,ge),ge=r.add($,ue),oe=r.sub(oe,ge),ge=r.add(S,M),U=r.add(D,B),ge=r.mul(ge,U),U=r.add(ne,ue),ge=r.sub(ge,U),z=r.mul(ee,oe),U=r.mul(te,ue),z=r.add(U,z),U=r.sub(ne,z),z=r.add(ne,z),C=r.mul(U,z),ne=r.add($,$),ne=r.add(ne,$),ue=r.mul(ee,ue),oe=r.mul(te,oe),ne=r.add(ne,ue),ue=r.sub($,ue),ue=r.mul(ee,ue),oe=r.add(oe,ue),$=r.mul(ne,oe),C=r.add(C,$),$=r.mul(ge,oe),U=r.mul(Z,U),U=r.sub(U,$),$=r.mul(Z,ne),z=r.mul(ge,z),z=r.add(z,$),new _(U,C,z)}subtract(h){return this.add(h.negate())}is0(){return this.equals(_.ZERO)}multiply(h){let{endo:x}=e;if(!s.isValidNot0(h))throw new Error("invalid scalar: out of range");let S,M,H=D=>P.cached(this,D,B=>pn(_,B));if(x){let{k1neg:D,k1:B,k2neg:U,k2:C}=K(h),{p:z,f:ee}=H(B),{p:te,f:$}=H(C);M=ee.add($),S=W(x.beta,z,te,D,U)}else{let{p:D,f:B}=H(h);S=D,M=B}return pn(_,[S,M])[0]}multiplyUnsafe(h){let{endo:x}=e,S=this;if(!s.isValid(h))throw new Error("invalid scalar: out of range");if(h===Xe||S.is0())return _.ZERO;if(h===Bt)return S;if(P.hasCache(this))return this.multiply(h);if(x){let{k1neg:M,k1:H,k2neg:D,k2:B}=K(h),{p1:U,p2:C}=Os(_,S,H,B);return W(x.beta,U,C,M,D)}else return P.unsafe(S,h)}toAffine(h){return A(this,h)}isTorsionFree(){let{isTorsionFree:h}=e;return o===Bt?!0:h?h(_,this):P.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:h}=e;return o===Bt?this:h?h(_,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(h=!0){return qt(h,"isCompressed"),this.assertValidity(),g(_,this,h)}toHex(h=!0){return Pe(this.toBytes(h))}toString(){return``}}let F=s.BITS,P=new dr(_,e.endo?Math.ceil(F/2):F);return _.BASE.precompute(8),_}function Hs(n){return Uint8Array.of(n?2:3)}function Ds(n,e){return{secretKey:e.BYTES,publicKey:1+n.BYTES,publicKeyUncompressed:1+2*n.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Eo(n,e={}){let{Fn:t}=n,r=e.randomBytes||Ye,s=Object.assign(Ds(n.Fp,t),{seed:hn(t.ORDER)});function i(g){try{let f=t.fromBytes(g);return t.isValidNot0(f)}catch{return!1}}function o(g,f){let{publicKey:m,publicKeyUncompressed:b}=s;try{let v=g.length;return f===!0&&v!==m||f===!1&&v!==b?!1:!!n.fromBytes(g)}catch{return!1}}function a(g=r(s.seed)){return ur(ae(g,s.seed,"seed"),t.ORDER)}function l(g,f=!0){return n.BASE.multiply(t.fromBytes(g)).toBytes(f)}function c(g){let{secretKey:f,publicKey:m,publicKeyUncompressed:b}=s;if(!Ft(g)||"_lengths"in t&&t._lengths||f===m)return;let v=ae(g,void 0,"key").length;return v===m||v===b}function u(g,f,m=!0){if(c(g)===!0)throw new Error("first arg must be private key");if(c(f)===!1)throw new Error("second arg must be public key");let b=t.fromBytes(g);return n.fromBytes(f).multiply(b).toBytes(m)}let d={isValidSecretKey:i,isValidPublicKey:o,randomSecretKey:a},p=fr(a,l);return Object.freeze({getPublicKey:l,getSharedSecret:u,keygen:p,Point:n,utils:d,lengths:s})}function Us(n,e,t={}){pt(e),Kt(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),t=Object.assign({},t);let r=t.randomBytes||Ye,s=t.hmac||((x,S)=>st(e,x,S)),{Fp:i,Fn:o}=n,{ORDER:a,BITS:l}=o,{keygen:c,getPublicKey:u,getSharedSecret:d,utils:p,lengths:g}=Eo(n,t),f={prehash:!0,lowS:typeof t.lowS=="boolean"?t.lowS:!0,format:"compact",extraEntropy:!1},m=a*Ns>Bt;return x>S}function v(x,S){if(!o.isValidNot0(S))throw new Error(`invalid signature ${x}: out of range 1..Point.Fn.ORDER`);return S}function w(){if(m)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function T(x,S){mn(S);let M=g.signature,H=S==="compact"?M:S==="recovered"?M+1:void 0;return ae(x,H)}class O{r;s;recovery;constructor(S,M,H){if(this.r=v("r",S),this.s=v("s",M),H!=null){if(w(),![0,1,2,3].includes(H))throw new Error("invalid recovery id");this.recovery=H}Object.freeze(this)}static fromBytes(S,M=f.format){T(S,M);let H;if(M==="der"){let{r:C,s:z}=it.toSig(ae(S));return new O(C,z)}M==="recovered"&&(H=S[0],M="compact",S=S.subarray(1));let D=g.signature/2,B=S.subarray(0,D),U=S.subarray(D,D*2);return new O(o.fromBytes(B),o.fromBytes(U),H)}static fromHex(S,M){return this.fromBytes(Te(S),M)}assertRecovery(){let{recovery:S}=this;if(S==null)throw new Error("invalid recovery id: must be present");return S}addRecoveryBit(S){return new O(this.r,this.s,S)}recoverPublicKey(S){let{r:M,s:H}=this,D=this.assertRecovery(),B=D===2||D===3?M+a:M;if(!i.isValid(B))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let U=i.toBytes(B),C=n.fromBytes(be(Hs((D&1)===0),U)),z=o.inv(B),ee=A(ae(S,void 0,"msgHash")),te=o.create(-ee*z),$=o.create(H*z),ne=n.BASE.multiplyUnsafe(te).add(C.multiplyUnsafe($));if(ne.is0())throw new Error("invalid recovery: point at infinify");return ne.assertValidity(),ne}hasHighS(){return b(this.s)}toBytes(S=f.format){if(mn(S),S==="der")return Te(it.hexFromSig(this));let{r:M,s:H}=this,D=o.toBytes(M),B=o.toBytes(H);return S==="recovered"?(w(),be(Uint8Array.of(this.assertRecovery()),D,B)):be(D,B)}toHex(S){return Pe(this.toBytes(S))}}let K=t.bits2int||function(S){if(S.length>8192)throw new Error("input is too large");let M=nt(S),H=S.length*8-l;return H>0?M>>BigInt(H):M},A=t.bits2int_modN||function(S){return o.create(K(S))},k=Wt(l);function W(x){return gs("num < 2^"+l,x,Xe,k),o.toBytes(x)}function _(x,S){return ae(x,void 0,"message"),S?ae(e(x),void 0,"prehashed message"):x}function F(x,S,M){let{lowS:H,prehash:D,extraEntropy:B}=gn(M,f);x=_(x,D);let U=A(x),C=o.fromBytes(S);if(!o.isValidNot0(C))throw new Error("invalid private key");let z=[W(C),W(U)];if(B!=null&&B!==!1){let ne=B===!0?r(g.secretKey):B;z.push(ae(ne,void 0,"extraEntropy"))}let ee=be(...z),te=U;function $(ne){let ue=K(ne);if(!o.isValidNot0(ue))return;let Z=o.inv(ue),oe=n.BASE.multiply(ue).toAffine(),ge=o.create(oe.x);if(ge===Xe)return;let Oe=o.create(Z*o.create(te+ge*C));if(Oe===Xe)return;let Ke=(oe.x===ge?0:2)|Number(oe.y&Bt),Ee=Oe;return H&&b(Oe)&&(Ee=o.neg(Oe),Ke^=1),new O(ge,Ee,m?void 0:Ke)}return{seed:ee,k2sig:$}}function P(x,S,M={}){let{seed:H,k2sig:D}=F(x,S,M);return ms(e.outputLen,o.BYTES,s)(H,D).toBytes(M.format)}function N(x,S,M,H={}){let{lowS:D,prehash:B,format:U}=gn(H,f);if(M=ae(M,void 0,"publicKey"),S=_(S,B),!Ft(x)){let C=x instanceof O?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+C)}T(x,U);try{let C=O.fromBytes(x,U),z=n.fromBytes(M);if(D&&C.hasHighS())return!1;let{r:ee,s:te}=C,$=A(S),ne=o.inv(te),ue=o.create($*ne),Z=o.create(ee*ne),oe=n.BASE.multiplyUnsafe(ue).add(z.multiplyUnsafe(Z));return oe.is0()?!1:o.create(oe.x)===ee}catch{return!1}}function h(x,S,M={}){let{prehash:H}=gn(M,f);return S=_(S,H),O.fromBytes(x,"recovered").recoverPublicKey(S).toBytes()}return Object.freeze({keygen:c,getPublicKey:u,getSharedSecret:d,utils:p,lengths:g,Point:n,sign:P,verify:N,recoverPublicKey:h,Signature:O,hash:e})}var br={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Ao={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},ko=BigInt(0),bn=BigInt(2);function Mo(n){let e=br.p,t=BigInt(3),r=BigInt(6),s=BigInt(11),i=BigInt(22),o=BigInt(23),a=BigInt(44),l=BigInt(88),c=n*n*n%e,u=c*c*n%e,d=_e(u,t,e)*u%e,p=_e(d,t,e)*u%e,g=_e(p,bn,e)*c%e,f=_e(g,s,e)*g%e,m=_e(f,i,e)*f%e,b=_e(m,a,e)*m%e,v=_e(b,l,e)*b%e,w=_e(v,a,e)*m%e,T=_e(w,t,e)*u%e,O=_e(T,o,e)*f%e,K=_e(O,r,e)*c%e,A=_e(K,bn,e);if(!mr.eql(mr.sqr(A),n))throw new Error("Cannot find square root");return A}var mr=kt(br.p,{sqrt:Mo}),yt=Ps(br,{Fp:mr,endo:Ao}),qs=Us(yt,Fe),zs={};function yr(n,...e){let t=zs[n];if(t===void 0){let r=Fe(ps(n));t=be(r,r),zs[n]=t}return Fe(be(t,...e))}var vn=n=>n.toBytes(!0).slice(1),xn=n=>n%bn===ko;function wn(n){let{Fn:e,BASE:t}=yt,r=e.fromBytes(n),s=t.multiply(r);return{scalar:xn(s.y)?r:e.neg(r),bytes:vn(s)}}function js(n){let e=mr;if(!e.isValidNot0(n))throw new Error("invalid x: Fail if x \u2265 p");let t=e.create(n*n),r=e.create(t*n+BigInt(7)),s=e.sqrt(r);xn(s)||(s=e.neg(s));let i=yt.fromAffine({x:n,y:s});return i.assertValidity(),i}var $t=nt;function Ws(...n){return yt.Fn.create($t(yr("BIP0340/challenge",...n)))}function Fs(n){return wn(n).bytes}function Bo(n,e,t=Ye(32)){let{Fn:r}=yt,s=ae(n,void 0,"message"),{bytes:i,scalar:o}=wn(e),a=ae(t,32,"auxRand"),l=r.toBytes(o^$t(yr("BIP0340/aux",a))),c=yr("BIP0340/nonce",l,i,s),{bytes:u,scalar:d}=wn(c),p=Ws(u,i,s),g=new Uint8Array(64);if(g.set(u,0),g.set(r.toBytes(r.create(d+p*o)),32),!Ks(g,s,i))throw new Error("sign: Invalid signature produced");return g}function Ks(n,e,t){let{Fp:r,Fn:s,BASE:i}=yt,o=ae(n,64,"signature"),a=ae(e,void 0,"message"),l=ae(t,32,"publicKey");try{let c=js($t(l)),u=$t(o.subarray(0,32));if(!r.isValidNot0(u))return!1;let d=$t(o.subarray(32,64));if(!s.isValidNot0(d))return!1;let p=Ws(s.toBytes(u),vn(c),a),g=i.multiplyUnsafe(d).add(c.multiplyUnsafe(s.neg(p))),{x:f,y:m}=g.toAffine();return!(g.is0()||!xn(m)||f!==u)}catch{return!1}}var Rt=(()=>{let t=(r=Ye(48))=>ur(r,br.n);return{keygen:fr(t,Fs),getPublicKey:Fs,sign:Bo,verify:Ks,Point:yt,utils:{randomSecretKey:t,taggedHash:yr,lift_x:js,pointToBytes:vn},lengths:{secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:64,seed:48}}})();var lc=new TextDecoder("utf-8"),Ro=new TextEncoder;function To(n){for(let e=0;e<64;e++){let t=n.charCodeAt(e);if(isNaN(t)||t<48||t>102||t>57&&t<97)return!1}return!0}var Tt=Symbol("verified"),Lo=n=>n instanceof Object;function _o(n){if(!Lo(n)||typeof n.kind!="number"||typeof n.content!="string"||typeof n.created_at!="number"||typeof n.pubkey!="string"||!To(n.pubkey)||!Array.isArray(n.tags))return!1;for(let e=0;e{function t(r,...s){if(we(r,void 0,"key"),!Po)throw new Error("Non little-endian hardware is not yet supported");if(n.nonceLength!==void 0){let u=s[0];we(u,n.varSizeNonce?void 0:n.nonceLength,"nonce")}let i=n.tagLength;i&&s[1]!==void 0&&we(s[1],void 0,"AAD");let o=e(r,...s),a=(u,d)=>{if(d!==void 0){if(u!==2)throw new Error("cipher output not supported");we(d,void 0,"output")}},l=!1;return{encrypt(u,d){if(l)throw new Error("cannot encrypt() twice with same key + nonce");return l=!0,we(u),a(o.encrypt.length,d),o.encrypt(u,d)},decrypt(u,d){if(we(u),i&&u.lengthUint8Array.from(n.split(""),e=>e.charCodeAt(0)),Do=Xs("expand 16-byte k"),Uo=Xs("expand 32-byte k"),zo=Je(Do),Fo=Je(Uo);function G(n,e){return n<>>32-e}function kn(n){return n.byteOffset%4===0}var Ar=64,qo=16,Js=2**32-1,Zs=Uint32Array.of();function jo(n,e,t,r,s,i,o,a){let l=s.length,c=new Uint8Array(Ar),u=Je(c),d=kn(s)&&kn(i),p=d?Je(s):Zs,g=d?Je(i):Zs;for(let f=0;f=Js)throw new Error("arx: counter overflow");let m=Math.min(Ar,l-f);if(d&&m===Ar){let b=f/4;if(f%4!==0)throw new Error("arx: invalid block position");for(let v=0,w;v{we(a,void 0,"key"),we(l,void 0,"nonce"),we(c,void 0,"data");let p=c.length;if(u===void 0&&(u=new Uint8Array(p)),we(u,void 0,"output"),Sr(d),d<0||d>=Js)throw new Error("arx: counter overflow");if(u.length>>13|r<<3)&8191,this.r[2]=(r>>>10|s<<6)&7939,this.r[3]=(s>>>7|i<<9)&8191,this.r[4]=(i>>>4|o<<12)&255,this.r[5]=o>>>1&8190,this.r[6]=(o>>>14|a<<2)&8191,this.r[7]=(a>>>11|l<<5)&8065,this.r[8]=(l>>>8|c<<8)&8191,this.r[9]=c>>>5&127;for(let u=0;u<8;u++)this.pad[u]=xe(e,16+2*u)}process(e,t,r=!1){let s=r?0:2048,{h:i,r:o}=this,a=o[0],l=o[1],c=o[2],u=o[3],d=o[4],p=o[5],g=o[6],f=o[7],m=o[8],b=o[9],v=xe(e,t+0),w=xe(e,t+2),T=xe(e,t+4),O=xe(e,t+6),K=xe(e,t+8),A=xe(e,t+10),k=xe(e,t+12),W=xe(e,t+14),_=i[0]+(v&8191),F=i[1]+((v>>>13|w<<3)&8191),P=i[2]+((w>>>10|T<<6)&8191),N=i[3]+((T>>>7|O<<9)&8191),h=i[4]+((O>>>4|K<<12)&8191),x=i[5]+(K>>>1&8191),S=i[6]+((K>>>14|A<<2)&8191),M=i[7]+((A>>>11|k<<5)&8191),H=i[8]+((k>>>8|W<<8)&8191),D=i[9]+(W>>>5|s),B=0,U=B+_*a+F*(5*b)+P*(5*m)+N*(5*f)+h*(5*g);B=U>>>13,U&=8191,U+=x*(5*p)+S*(5*d)+M*(5*u)+H*(5*c)+D*(5*l),B+=U>>>13,U&=8191;let C=B+_*l+F*a+P*(5*b)+N*(5*m)+h*(5*f);B=C>>>13,C&=8191,C+=x*(5*g)+S*(5*p)+M*(5*d)+H*(5*u)+D*(5*c),B+=C>>>13,C&=8191;let z=B+_*c+F*l+P*a+N*(5*b)+h*(5*m);B=z>>>13,z&=8191,z+=x*(5*f)+S*(5*g)+M*(5*p)+H*(5*d)+D*(5*u),B+=z>>>13,z&=8191;let ee=B+_*u+F*c+P*l+N*a+h*(5*b);B=ee>>>13,ee&=8191,ee+=x*(5*m)+S*(5*f)+M*(5*g)+H*(5*p)+D*(5*d),B+=ee>>>13,ee&=8191;let te=B+_*d+F*u+P*c+N*l+h*a;B=te>>>13,te&=8191,te+=x*(5*b)+S*(5*m)+M*(5*f)+H*(5*g)+D*(5*p),B+=te>>>13,te&=8191;let $=B+_*p+F*d+P*u+N*c+h*l;B=$>>>13,$&=8191,$+=x*a+S*(5*b)+M*(5*m)+H*(5*f)+D*(5*g),B+=$>>>13,$&=8191;let ne=B+_*g+F*p+P*d+N*u+h*c;B=ne>>>13,ne&=8191,ne+=x*l+S*a+M*(5*b)+H*(5*m)+D*(5*f),B+=ne>>>13,ne&=8191;let ue=B+_*f+F*g+P*p+N*d+h*u;B=ue>>>13,ue&=8191,ue+=x*c+S*l+M*a+H*(5*b)+D*(5*m),B+=ue>>>13,ue&=8191;let Z=B+_*m+F*f+P*g+N*p+h*d;B=Z>>>13,Z&=8191,Z+=x*u+S*c+M*l+H*a+D*(5*b),B+=Z>>>13,Z&=8191;let oe=B+_*b+F*m+P*f+N*g+h*p;B=oe>>>13,oe&=8191,oe+=x*d+S*u+M*c+H*l+D*a,B+=oe>>>13,oe&=8191,B=(B<<2)+B|0,B=B+U|0,U=B&8191,B=B>>>13,C+=B,i[0]=U,i[1]=C,i[2]=z,i[3]=ee,i[4]=te,i[5]=$,i[6]=ne,i[7]=ue,i[8]=Z,i[9]=oe}finalize(){let{h:e,pad:t}=this,r=new Uint16Array(10),s=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=s,s=e[a]>>>13,e[a]&=8191;e[0]+=s*5,s=e[0]>>>13,e[0]&=8191,e[1]+=s,s=e[1]>>>13,e[1]&=8191,e[2]+=s,r[0]=e[0]+5,s=r[0]>>>13,r[0]&=8191;for(let a=1;a<10;a++)r[a]=e[a]+s,s=r[a]>>>13,r[a]&=8191;r[9]-=8192;let i=(s^1)-1;for(let a=0;a<10;a++)r[a]&=i;i=~i;for(let a=0;a<10;a++)e[a]=e[a]&i|r[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let o=e[0]+t[0];e[0]=o&65535;for(let a=1;a<8;a++)o=(e[a]+t[a]|0)+(o>>>16)|0,e[a]=o&65535;Qe(r)}update(e){Sn(this),we(e),e=Lt(e);let{buffer:t,blockLen:r}=this,s=e.length;for(let i=0;i>>0,e[i++]=r[o]>>>8;return e}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}};function Wo(n){let e=(r,s)=>n(s).update(r).digest(),t=n(new Uint8Array(32));return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=r=>n(r),e}var Qs=Wo(n=>new Bn(n));function ri(n,e,t,r,s,i=20){let o=n[0],a=n[1],l=n[2],c=n[3],u=e[0],d=e[1],p=e[2],g=e[3],f=e[4],m=e[5],b=e[6],v=e[7],w=s,T=t[0],O=t[1],K=t[2],A=o,k=a,W=l,_=c,F=u,P=d,N=p,h=g,x=f,S=m,M=b,H=v,D=w,B=T,U=O,C=K;for(let ee=0;ee{n.update(e);let t=e.length%16;t&&n.update($o.subarray(t))},Go=new Uint8Array(32);function ti(n,e,t,r,s){s!==void 0&&we(s,void 0,"AAD");let i=n(e,t,Go),o=Ys(r.length,s?s.length:0,!0),a=Qs.create(i);s&&ei(a,s),ei(a,r),a.update(o);let l=a.digest();return Qe(i,o),l}var ni=n=>(e,t,r)=>({encrypt(i,o){let a=i.length;o=An(a+16,o,!1),o.set(i);let l=o.subarray(0,-16);n(e,t,l,l,1);let c=ti(n,e,t,l,r);return o.set(c,a),Qe(c),o},decrypt(i,o){o=An(i.length-16,o,!1);let a=i.subarray(0,-16),l=i.subarray(-16),c=ti(n,e,t,a,r);if(!Er(l,c))throw new Error("invalid tag");return o.set(i.subarray(0,-16)),n(e,t,o,o,1),Qe(c),o}}),Mc=En({blockSize:64,nonceLength:12,tagLength:16},ni(kr)),Bc=En({blockSize:64,nonceLength:24,tagLength:16},ni(Vo));function ii(n,e,t){return pt(n),t===void 0&&(t=new Uint8Array(n.outputLen)),st(n,t,e)}var Rn=Uint8Array.of(0),si=Uint8Array.of();function oi(n,e,t,r=32){pt(n),Ne(r,"length");let s=n.outputLen;if(r>255*s)throw new Error("Length must be <= 255*HashLen");let i=Math.ceil(r/s);t===void 0?t=si:ae(t,void 0,"info");let o=new Uint8Array(i*s),a=st.create(n,e),l=a._cloneInto(),c=new Uint8Array(a.outputLen);for(let u=0;utypeof t=="string"):e.every(t=>Number.isSafeInteger(t)):!1}function Xt(n,e){if(typeof e!="string")throw new Error(`${n}: string expected`);return!0}function _n(n){if(!Number.isSafeInteger(n))throw new Error(`invalid integer: ${n}`)}function Ln(n){if(!Array.isArray(n))throw new Error("array expected")}function Mr(n,e){if(!ci(!0,e))throw new Error(`${n}: array of strings expected`)}function Zo(n,e){if(!ci(!1,e))throw new Error(`${n}: array of numbers expected`)}function Xo(...n){let e=i=>i,t=(i,o)=>a=>i(o(a)),r=n.map(i=>i.encode).reduceRight(t,e),s=n.map(i=>i.decode).reduce(t,e);return{encode:r,decode:s}}function Jo(n){let e=typeof n=="string"?n.split(""):n,t=e.length;Mr("alphabet",e);let r=new Map(e.map((s,i)=>[s,i]));return{encode:s=>(Ln(s),s.map(i=>{if(!Number.isSafeInteger(i)||i<0||i>=t)throw new Error(`alphabet.encode: digit index outside alphabet "${i}". Allowed: ${n}`);return e[i]})),decode:s=>(Ln(s),s.map(i=>{Xt("alphabet.decode",i);let o=r.get(i);if(o===void 0)throw new Error(`Unknown letter: "${i}". Allowed: ${n}`);return o}))}}function Qo(n=""){return Xt("join",n),{encode:e=>(Mr("join.decode",e),e.join(n)),decode:e=>(Xt("join.decode",e),e.split(n))}}function ea(n,e="="){return _n(n),Xt("padding",e),{encode(t){for(Mr("padding.encode",t);t.length*n%8;)t.push(e);return t},decode(t){Mr("padding.decode",t);let r=t.length;if(r*n%8)throw new Error("padding: invalid, string should have whole number of bytes");for(;r>0&&t[r-1]===e;r--)if((r-1)*n%8===0)throw new Error("padding: invalid, string has too much padding");return t.slice(0,r)}}}var hi=(n,e)=>e===0?n:hi(e,n%e),Br=(n,e)=>n+(e-hi(n,e)),Tn=(()=>{let n=[];for(let e=0;e<40;e++)n.push(2**e);return n})();function ai(n,e,t,r){if(Ln(n),e<=0||e>32)throw new Error(`convertRadix2: wrong from=${e}`);if(t<=0||t>32)throw new Error(`convertRadix2: wrong to=${t}`);if(Br(e,t)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${t} carryBits=${Br(e,t)}`);let s=0,i=0,o=Tn[e],a=Tn[t]-1,l=[];for(let c of n){if(_n(c),c>=o)throw new Error(`convertRadix2: invalid data word=${c} from=${e}`);if(s=s<32)throw new Error(`convertRadix2: carry overflow pos=${i} from=${e}`);for(i+=e;i>=t;i-=t)l.push((s>>i-t&a)>>>0);let u=Tn[i];if(u===void 0)throw new Error("invalid carry");s&=u-1}if(s=s<=e)throw new Error("Excess padding");if(!r&&s>0)throw new Error(`Non-zero padding: ${s}`);return r&&i>0&&l.push(s>>>0),l}function ta(n,e=!1){if(_n(n),n<=0||n>32)throw new Error("radix2: bits should be in (0..32]");if(Br(8,n)>32||Br(n,8)>32)throw new Error("radix2: carry overflow");return{encode:t=>{if(!li(t))throw new Error("radix2.encode input should be Uint8Array");return ai(Array.from(t),8,n,!e)},decode:t=>(Zo("radix2.decode",t),Uint8Array.from(ai(t,n,8,e)))}}var ra=typeof Uint8Array.from([]).toBase64=="function"&&typeof Uint8Array.fromBase64=="function",na=(n,e)=>{Xt("base64",n);let t=e?/^[A-Za-z0-9=_-]+$/:/^[A-Za-z0-9=+/]+$/,r=e?"base64url":"base64";if(n.length>0&&!t.test(n))throw new Error("invalid base64");return Uint8Array.fromBase64(n,{alphabet:r,lastChunkHandling:"strict"})},On=ra?{encode(n){return Yo(n),n.toBase64()},decode(n){return na(n,!1)}}:Xo(ta(6),Jo("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),ea(6),Qo(""));var sa=new TextDecoder("utf-8"),ui=new TextEncoder,In=1,Cn=4294967295,Nn=65536;function ia(n,e){let t=qs.getSharedSecret(n,Te("02"+e)).subarray(1,33);return ii(Fe,t,ui.encode("nip44-v2"))}function di(n,e){let t=oi(Fe,n,e,76);return{chacha_key:t.subarray(0,32),chacha_nonce:t.subarray(32,44),hmac_key:t.subarray(44,76)}}function Pn(n){if(!Number.isSafeInteger(n)||n<1)throw new Error("expected positive integer");if(n<=32)return 32;let e=2**(Math.floor(Math.log2(n-1))+1),t=e<=256?32:e/8;return t*(Math.floor((n-1)/t)+1)}function oa(n){if(!Number.isSafeInteger(n)||n65535)throw new Error("invalid plaintext size: must be between 1 and 65535 bytes");let e=new Uint8Array(2);return new DataView(e.buffer).setUint16(0,n,!1),e}function aa(n){if(!Number.isSafeInteger(n)||nCn)throw new Error("invalid plaintext size: must be between 65536 and 4294967295 bytes");let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,n,!1),e}function fi(n){let e=ui.encode(n),t=e.length;if(tCn)throw new Error("invalid plaintext size: must be between 1 and 4294967295 bytes");let r=t>=Nn?be(new Uint8Array([0,0]),aa(t)):oa(t),s=new Uint8Array(Pn(t)-t);return be(r,e,s)}function pi(n){let e=new DataView(n.buffer,n.byteOffset,n.byteLength),t=e.getUint16(0),r,s;if(t===0){if(r=e.getUint32(2),rCn||i.length!==r||n.length!==s+Pn(r))throw new Error("invalid padding");return sa.decode(i)}function gi(n,e,t){if(t.length!==32)throw new Error("AAD associated data must be 32 bytes");let r=be(t,e);return st(Fe,n,r)}function la(n){if(typeof n!="string")throw new Error("payload must be a valid string");let e=n.length;if(e<132)throw new Error("invalid payload length: "+e);if(n[0]==="#")throw new Error("unknown encryption version");let t;try{t=On.decode(n)}catch(i){throw new Error("invalid base64: "+i.message)}let r=t.length;if(r<99)throw new Error("invalid data length: "+r);let s=t[0];if(s!==2)throw new Error("unknown encryption version "+s);return{nonce:t.subarray(1,33),ciphertext:t.subarray(33,-32),mac:t.subarray(-32)}}function ca(n,e,t=Ye(32)){let{chacha_key:r,chacha_nonce:s,hmac_key:i}=di(e,t),o=fi(n),a=kr(r,s,o),l=gi(i,a,t);return On.encode(be(new Uint8Array([2]),t,a,l))}function ha(n,e){let{nonce:t,ciphertext:r,mac:s}=la(n),{chacha_key:i,chacha_nonce:o,hmac_key:a}=di(e,t),l=gi(a,r,t);if(!Er(l,s))throw new Error("invalid MAC");let c=kr(i,o,r);return pi(c)}var Rr={utils:{getConversationKey:ia,calcPaddedLen:Pn,pad:fi,unpad:pi},encrypt:ca,decrypt:ha};function Jt(n,e){if(n.ids&&n.ids.indexOf(e.id)===-1||n.kinds&&n.kinds.indexOf(e.kind)===-1||n.authors&&n.authors.indexOf(e.pubkey)===-1)return!1;for(let t in n)if(t[0]==="#"){let r=t.slice(1),s=n[`#${r}`];if(s&&!e.tags.find(([i,o])=>i===t.slice(1)&&s.indexOf(o)!==-1))return!1}return!(n.since&&e.created_atn.until)}var Tr=3,Lr=24170,Hn=24171,_r="x",Qt=/^[0-9a-f]{64}$/u,ua=/^[a-z0-9](?:[a-z0-9-]{0,31})$/u,da=1*1024*1024,mi=16*1024,fa=64*1024,yi=8*1024,pa=2*1024,bi=30,ga=64,ma=256,wi=new TextEncoder;function bt(n){return typeof n=="string"?wi.encode(n).byteLength:n instanceof ArrayBuffer||ArrayBuffer.isView(n)?n.byteLength:wi.encode(String(n)).byteLength}function ya(n){return Array.from(globalThis.crypto.getRandomValues(new Uint8Array(n)),e=>e.toString(16).padStart(2,"0")).join("")}function Ai(n,e){return Array.isArray(n?.tags)?n.tags.filter(t=>Array.isArray(t)&&t.length>=2&&t[0]===e&&typeof t[1]=="string").map(t=>t[1]):[]}var Dn=n=>Math.min(Number.MAX_SAFE_INTEGER,n);function vi(n,e){let t=Ai(n,e);return t.length===1?t[0]:null}function xi(n){let e=JSON.parse(n);if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Expected a JSON object.");return e}function ot(n){return typeof n=="string"&&ua.test(n)}function Si(n){return typeof n=="string"&&n.length>=8&&n.length<=64&&/^[a-zA-Z0-9_-]+$/u.test(n)}function ba(n){let e=new URL(String(n)),t=e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname==="[::1]";if(e.protocol!=="wss:"&&!(e.protocol==="ws:"&&t))throw new Error("Relay URLs must use wss://, except for loopback tests.");return e.username="",e.password="",e.hash="",e.toString()}var Or=class{constructor(e,{label:t="relay",WebSocketImpl:r=globalThis.WebSocket,connectTimeoutMs:s=8e3,reconnect:i=!1,reconnectMaxMs:o=3e4,readyOnFirstRelay:a=!1}={}){if(!Array.isArray(e)||e.length<1||e.length>8)throw new Error("RelayPool requires between one and eight relay URLs.");if(typeof r!="function")throw new Error("RelayPool requires a WebSocket implementation.");this.urls=[...new Set(e.map(ba))],this.label=t,this.WebSocketImpl=r,this.connectTimeoutMs=s,this.sockets=[],this.handlers=new Set,this.relayOpenHandlers=new Set,this.seen=new Set,this.connected=!1,this.closed=!1,this.connecting=null,this.pendingSockets=new Map,this.readyWaiters=new Set,this.reconnect=i,this.readyOnFirstRelay=a===!0,this.reconnectMaxMs=o,this.subscriptions=new Map,this.retryTimers=new Set,this.published=0,this.rejected=0,this.rejectedTimestamp=0,this.sinceDropped=0,this.rejectHandlers=new Set}async connect(){if(this.closed)throw new Error("RelayPool is closed.");if(!(this.connected&&this.sockets.length))return this.connecting?this.connecting:(this.connecting=this.#r().finally(()=>{this.connecting=null}),this.connecting)}async#r(){this.connected=!0;let e,t=this.reconnect||this.readyOnFirstRelay?new Promise((o,a)=>this.readyWaiters.add(e={resolve:o,reject:a})):null,r=Promise.allSettled(this.urls.map(o=>this.#t(o))),s=o=>{let a=o.map(l=>l.status==="rejected"?l.reason?.message:"").filter(Boolean);return new Error(`No relay reachable${a.length?`: ${a.join("; ")}`:"."}`)};if(this.reconnect){r.then(o=>{this.closed||o.forEach((a,l)=>{a.status==="rejected"&&this.#e(this.urls[l],1)})}).catch(o=>e.reject(o));try{if(await t,this.closed)throw new Error("RelayPool is closed.")}finally{this.readyWaiters.delete(e)}return}if(t){r.then(o=>{this.sockets.length===0&&e.reject(s(o))});try{if(await t,this.closed)throw new Error("RelayPool is closed.")}finally{this.readyWaiters.delete(e)}return}let i=await r;if(this.closed)throw new Error("RelayPool is closed.");if(this.sockets.length===0)throw s(i);this.connected=!0}#t(e){return new Promise((t,r)=>{let s=!1,i=new this.WebSocketImpl(e),o=l=>{if(!s)if(s=!0,clearTimeout(a),this.pendingSockets.delete(i),l){try{i.close()}catch{}r(l)}else t(i)},a=setTimeout(()=>{o(new Error(`${e} timed out`))},this.connectTimeoutMs);this.pendingSockets.set(i,()=>o(new Error("RelayPool is closed."))),i.addEventListener("open",()=>{if(s||this.closed){try{i.close()}catch{}return}this.sockets.push(i);for(let[c,u]of this.subscriptions)i.send(JSON.stringify(["REQ",c,u]));o();for(let c of this.readyWaiters)c.resolve();this.readyWaiters.clear();let l=c=>{if(this.closed||!this.sockets.includes(i))return!1;try{return i.send(JSON.stringify(["EVENT",c])),this.published+=1,!0}catch{return!1}};for(let c of[...this.relayOpenHandlers])try{c(l)}catch{}}),i.addEventListener("error",()=>o(new Error(`${e} failed to connect`))),i.addEventListener("message",l=>this.#s(l.data)),i.addEventListener("close",()=>{let l=this.sockets.includes(i);this.sockets=this.sockets.filter(c=>c!==i),o(new Error(`${e} closed`)),this.reconnect&&this.connected&&l&&this.#e(e,1)})})}#e(e,t){if(this.closed)return;let r=Math.min(this.reconnectMaxMs,1e3*2**Math.min(t,5))*(.5+Math.random()*.5),s=setTimeout(()=>{this.retryTimers.delete(s),this.connected&&this.#t(e).catch(()=>{this.connected&&!this.sockets.some(i=>i.url===e)&&this.#e(e,t+1)})},r);this.retryTimers.add(s)}#s(e){if(this.closed||bt(e)>da)return;let t;try{t=JSON.parse(String(e))}catch{return}if(Array.isArray(t)&&t[0]==="OK"&&t[2]===!1){this.rejected+=1,/created_at|timestamp|future|too (old|far|new)/i.test(String(t[3]||""))&&(this.rejectedTimestamp=Math.min(Number.MAX_SAFE_INTEGER,this.rejectedTimestamp+1));for(let i of this.rejectHandlers)try{i({id:t[1],message:String(t[3]||"")})}catch{}return}if(!Array.isArray(t)||t[0]!=="EVENT"||!t[2]||typeof t[2]!="object")return;let r=t[2],s=this.subscriptions.get(t[1]);try{s&&!Jt(s,r)&&s.since&&Number.isSafeInteger(r.created_at)&&r.created_at1e4&&this.seen.delete(this.seen.values().next().value);for(let i of this.handlers)i(r)}subscribe(e){if(!this.connected||this.sockets.length===0)throw new Error("RelayPool is not connected.");if(this.subscriptions.size>=32)throw new Error("Relay subscription capacity reached.");let t=ya(8),r=JSON.stringify(["REQ",t,e]);this.subscriptions.set(t,e);for(let s of this.sockets)s.send(r);return t}unsubscribe(e){if(this.subscriptions.delete(e))for(let t of this.sockets)try{t.send(JSON.stringify(["CLOSE",e]))}catch{}}onReject(e){return this.rejectHandlers.add(e),()=>this.rejectHandlers.delete(e)}onEvent(e){return this.handlers.add(e),()=>this.handlers.delete(e)}onRelayOpen(e){return this.relayOpenHandlers.add(e),()=>this.relayOpenHandlers.delete(e)}publish(e){if(!this.connected||this.sockets.length===0)throw new Error("RelayPool has no connected relay.");let t=JSON.stringify(["EVENT",e]);for(let r of this.sockets)r.send(t);this.published+=1}close(){this.closed=!0,this.connected=!1;for(let e of this.retryTimers)clearTimeout(e);this.retryTimers.clear(),this.subscriptions.clear(),this.rejectHandlers.clear();for(let e of[...this.pendingSockets.values()])e();this.pendingSockets.clear();for(let e of this.readyWaiters)e.reject(new Error("RelayPool is closed."));this.readyWaiters.clear();for(let e of this.sockets)try{e.close()}catch{}this.sockets=[],this.handlers.clear(),this.relayOpenHandlers.clear(),this.seen.clear()}},Ir=class{#r=null;#t=null;#e=new Map;#s=null;constructor({pool:e,swarmId:t,secretKey:r=Yt(),maxEventAgeSeconds:s=120}={}){if(!e)throw new Error("RelaySwarmSession requires a relay pool.");if(typeof t!="string"||t.length<8||t.length>128)throw new Error("Invalid swarm identifier.");this.pool=e,this.swarmId=t,this.secretKey=r,this.pubkey=Vs(r),this.maxEventAgeSeconds=s,this.presenceHandlers=new Set,this.signalHandlers=new Set,this.errorHandlers=new Set,this.started=!1,this.unsubscribe=null,this.subscriptionIds=[],this.clock={aheadRejected:0,staleRejected:0,maxAheadSeconds:0,signalAges:[]}}clockDiagnostics(){let e=[...this.clock.signalAges].sort((t,r)=>t-r);return{aheadRejected:this.clock.aheadRejected,staleRejected:this.clock.staleRejected,maxAheadSeconds:this.clock.maxAheadSeconds,signalSamples:e.length,signalAgeMedianSeconds:e.length?e[Math.floor(e.length/2)]:null}}start(){if(this.started)return;this.started=!0,this.unsubscribe=this.pool.onEvent(t=>this.#i(t));let e={[`#${_r}`]:[this.swarmId],since:Math.floor(Date.now()/1e3)-2};try{this.#t=this.pool.onRelayOpen?.(t=>{if(!this.started||!this.#r)return;let r=Math.floor(Date.now()/1e3)-this.#r.created_at;if(!Number.isFinite(r)||!Number.isFinite(this.maxEventAgeSeconds)||r<-bi||r>this.maxEventAgeSeconds){this.#r=null;return}t(this.#r)}),this.subscriptionId=this.pool.subscribe({...e,since:Math.floor(Date.now()/1e3)-this.maxEventAgeSeconds,kinds:[Lr]}),this.subscriptionIds.push(this.subscriptionId),this.subscriptionIds.push(this.pool.subscribe({...e,kinds:[Hn],"#p":[this.pubkey]}))}catch(t){for(let r of this.subscriptionIds)this.pool.unsubscribe?.(r);throw this.subscriptionIds=[],this.unsubscribe?.(),this.unsubscribe=null,this.started=!1,this.#t?.(),this.#t=null,this.#r=null,t}}onPresence(e){return this.presenceHandlers.add(e),()=>this.presenceHandlers.delete(e)}onSignal(e){return this.signalHandlers.add(e),()=>this.signalHandlers.delete(e)}onError(e){return this.errorHandlers.add(e),()=>this.errorHandlers.delete(e)}announcePresence({role:e,transports:t=[],have:r=[],open:s,ticket:i}={}){if(i!==void 0&&!ye(i))throw new Error("Invalid presence ticket.");if(!ot(e))throw new Error("Invalid presence role.");if(!Array.isArray(t)||t.length>8)throw new Error("Invalid transport capability list.");if(!Array.isArray(r)||r.length>32||r.some(c=>!Qt.test(c)))throw new Error("Invalid object hash list.");let o=t.map(c=>{if(!c||typeof c!="object"||!ot(c.type)||!Qt.test(c.publicKey)||c.obj!==void 0&&!Ei(c.obj))throw new Error("Invalid transport capability.");return{type:c.type,publicKey:c.publicKey,...c.obj===void 0?{}:{obj:c.obj}}}),a=JSON.stringify({v:Tr,role:e,transports:o,have:[...new Set(r)],...s===void 0?{}:{open:!!s},...i===void 0?{}:{ticket:i}});if(bt(a)>mi)throw new Error("Presence payload is too large.");let l=vr({kind:Lr,created_at:Math.floor(Date.now()/1e3),tags:[[_r,this.swarmId]],content:a},this.secretKey);return this.pool.publish(l),this.#r=JSON.parse(JSON.stringify(l)),l}sendSignal(e,{type:t,transport:r,requestId:s,payload:i={}}={}){if(!Qt.test(e))throw new Error("Invalid signal recipient.");if(!ot(t)||!ot(r)||!Si(s))throw new Error("Invalid signal envelope.");if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Invalid signal payload.");let o=JSON.stringify({v:Tr,type:t,transport:r,requestId:s,payload:i});if(bt(o)>yi)throw new Error("Signal payload is too large.");let a=Rr.encrypt(o,this.#n(e)),l=vr({kind:Hn,created_at:Math.floor(Date.now()/1e3),tags:[[_r,this.swarmId],["p",e]],content:a},this.secretKey);return this.pool.publish(l),l}waitForPresence(e,t=15e3){return this.#d(this.presenceHandlers,e,t,"Timed out waiting for RelaySwarm presence.")}waitForSignal(e,t=15e3){return this.#d(this.signalHandlers,e,t,"Timed out waiting for RelaySwarm signal.")}#d(e,t,r,s){return new Promise((i,o)=>{let a=c=>{let u=!1;try{u=t(c)}catch(d){clearTimeout(l),e.delete(a),o(d);return}u&&(clearTimeout(l),e.delete(a),i(c))},l=setTimeout(()=>{e.delete(a),o(new Error(s))},r);e.add(a)})}#i(e){if(e.pubkey===this.pubkey||e.kind!==Lr&&e.kind!==Hn||!Number.isSafeInteger(e.created_at)||vi(e,_r)!==this.swarmId)return;let t=Math.floor(Date.now()/1e3)-e.created_at;if(t<-bi){this.clock.aheadRejected=Dn(this.clock.aheadRejected+1),this.clock.maxAheadSeconds=Math.max(this.clock.maxAheadSeconds,Dn(-t));return}if(t>this.maxEventAgeSeconds){this.clock.staleRejected=Dn(this.clock.staleRejected+1);return}try{e.kind===Lr?this.#c(e):this.#o(e)}catch{}}#c(e){if(bt(e.content)>mi||Ai(e,"p").length!==0)return;let t=xi(e.content);if(t.v!==Tr||!ot(t.role)||!Array.isArray(t.transports)||t.transports.length>8||!Array.isArray(t.have)||t.have.length>32||t.have.some(o=>!Qt.test(o)))return;let r=t.transports.map(o=>{if(!o||typeof o!="object"||!ot(o.type)||!Qt.test(o.publicKey))throw new Error("Invalid transport capability.");return{type:o.type,publicKey:o.publicKey,...Ei(o.obj)?{obj:o.obj}:{}}}),s=typeof t.open=="boolean"?t.open:null,i=ye(t.ticket)?t.ticket:null;this.#h(this.presenceHandlers,{from:e.pubkey,event:e,payload:{...t,transports:r,open:s,ticket:i}})}#o(e){if(bt(e.content)>fa||vi(e,"p")!==this.pubkey)return;let t=Rr.decrypt(e.content,this.#n(e.pubkey));if(bt(t)>yi)return;let r=xi(t);r.v!==Tr||!ot(r.type)||!ot(r.transport)||!Si(r.requestId)||!r.payload||typeof r.payload!="object"||Array.isArray(r.payload)||(this.clock.signalAges.length>=ga&&this.clock.signalAges.shift(),this.clock.signalAges.push(Math.floor(Date.now()/1e3)-e.created_at),this.#h(this.signalHandlers,{from:e.pubkey,event:e,payload:r}))}#n(e){this.#s!==this.secretKey&&(this.#e.clear(),this.#s=this.secretKey);let t=this.#e.get(e);return t?this.#e.delete(e):(t=Rr.utils.getConversationKey(this.secretKey,e),this.#e.size>=ma&&this.#e.delete(this.#e.keys().next().value)),this.#e.set(e,t),t}#h(e,t){for(let r of e)Promise.resolve().then(()=>r(t)).catch(s=>{for(let i of this.errorHandlers)i(s)})}close(){this.unsubscribe?.(),this.#t?.(),this.#t=null,this.#r=null,this.#e.clear(),this.#s=null;for(let e of this.subscriptionIds)this.pool.unsubscribe?.(e);this.subscriptionIds=[],this.unsubscribe=null,this.started=!1,this.presenceHandlers.clear(),this.signalHandlers.clear(),this.errorHandlers.clear()}};function Ei(n){return Number.isSafeInteger(n)&&n>=1&&n<=15}function ye(n){return typeof n=="string"&&n.length>0&&bt(n)<=pa}var Un=/^[0-9a-f]{64}$/u,ki="relayswarm-abandon";var Mi=new Set(["host","host-stop","admission","rotation","integrity","request-timeout","request-abort","native-failed","native-closed","native-disconnected","channel-close","channel-error","protocol","send-error","serve-error","upload-queue","upload-drain-timeout"]),at=class{static ABANDON_REASON=ki;#r=!1;constructor({pubkey:e,pc:t,channel:r,maxSegmentBytes:s,onRequest:i,onHaveChange:o,onScheduleChange:a,onClose:l,onUploadCancelled:c,maxQueuedRequests:u=4,drainTimeoutMs:d=3e3}){this.pubkey=e,this.pc=t,this.channel=r,this.maxSegmentBytes=s,this.onRequest=i,this.onHaveChange=o,this.onScheduleChange=a,this.contribution={serving:!1,rendition:null,at:0},this.fetching=new Map,this.renditions=new Map,this.announced=new Map,this.onClose=l,this.onUploadCancelled=c,this.maxQueuedRequests=u,this.drainTimeoutMs=d,this.maxChunks=Math.max(1,Math.ceil(s/16384)*4),this.have=new Set,this.pending=null,this.nextId=1,this.serving=Promise.resolve(),this.closed=!1,this.openedAt=Date.now(),this.lastServedAt=0,this.lastDeliveredAt=0,this.outboundInFlight=0,this.uploads=new Set,this.bytesIn=0,this.bytesOut=0,r.binaryType="arraybuffer",r.bufferedAmountLowThreshold=32768,r.addEventListener("message",p=>{try{this.#e(p.data)}catch{this.close("protocol")}}),r.addEventListener("close",()=>this.close("channel-close")),r.addEventListener("error",()=>this.close("channel-error")),t.addEventListener("connectionstatechange",()=>{let p=t.connectionState;["failed","closed","disconnected"].includes(p)&&this.close(`native-${p}`)})}get busy(){return this.pending!==null}get transferring(){return this.pending!==null||this.outboundInFlight>0}get lastUsefulAt(){return Math.max(this.lastDeliveredAt,this.lastServedAt,this.openedAt)}sendHave(e){this.#t({t:"have",keys:e.slice(-256)})}sendHaveChange(e=[],t=[]){(e.length||t.length)&&this.#t({t:"have",add:e,del:t})}sendContribution(e,t){this.#t({t:"contribution",serving:e,rendition:t})}sendFetching(e,t=0){this.#t({t:"fetching",k:e,ms:t})}request(e,t,{signal:r,expectedSize:s,onResult:i,onProgress:o}={}){let a=null;try{a=performance.now()}catch{}let l=!1,c=(u,d=null)=>{if(!l&&(l=!0,typeof i=="function"))try{let p=null;if(Number.isFinite(a))try{p=performance.now()-a}catch{}let g=d?.received??0,f=Number.isFinite(d?.firstByteAt)&&Number.isFinite(a)?d.firstByteAt-a:null;i({outcome:u,elapsedMs:Number.isFinite(p)&&p>=0?p:null,timeoutMs:Number.isFinite(t)&&t>=0?t:null,expectedBytes:Number.isSafeInteger(s)&&s>=0?s:null,receivedBytes:Number.isSafeInteger(g)&&g>=0?g:null,firstByteMs:Number.isFinite(f)&&f>=0?f:null,metadataReceived:d?d.size>=0:!1,draining:d?.draining===!0,closeReason:Mi.has(this.closeReason)?this.closeReason:null})}catch{}};if(this.closed||this.pending||r?.aborted){let u=Promise.resolve(null);return c(this.closed?"closed":this.pending?"busy":"abort"),u}return new Promise(u=>{let d=this.nextId++,p=w=>{clearTimeout(this.pending.timer),r?.removeEventListener("abort",m),u(w)},g=(w,T=w?"payload":"none",O=!0)=>{if(this.pending?.id!==d)return;let K=this.pending,A=K.draining;p(w),this.pending=null,w&&(this.lastDeliveredAt=Date.now()),A&&!this.closed&&this.onScheduleChange?.(this),O&&c(T,K)},f=w=>{let T=this.pending;if(!T||T.id!==d||T.draining)return;let O=!1;try{O=this.channel.ordered===!0&&this.channel.maxRetransmits===null&&this.channel.maxPacketLifeTime===null&&this.channel.readyState==="open"}catch{}let K=w!=="request-abort"?"timeout":r?.reason===ki?"abandoned":"abort";if(!O){g(null,K,!1);try{this.close(w)}finally{c(K,T)}return}T.draining=!0,T.parts.length=0,p(null),T.timer=setTimeout(()=>{this.pending===T&&T.draining&&this.close(w)},this.drainTimeoutMs),c(K,T),T.cancelled=this.#t({t:"cancel",id:d})},m=()=>f("request-abort"),b=()=>f("request-timeout"),v=typeof o=="function"?w=>{try{o(w.received,w.size,Number.isFinite(a)?w.firstByteAt-a:null)}catch{}}:null;this.pending={id:d,key:e,expectedSize:s,size:-1,parts:[],chunks:0,received:0,firstByteAt:null,progress:v,draining:!1,cancelled:!1,finish:g,timer:setTimeout(b,Math.max(1,t))},r?.addEventListener("abort",m,{once:!0}),this.#t({t:"want",id:d,k:e})||g(null,"send-error")})}close(e="host"){if(!this.closed){this.closed=!0,this.closeReason=Mi.has(e)?e:"host",this.fetching.clear(),this.renditions.clear(),this.announced.clear(),this.pending?.finish(null,this.closeReason==="send-error"?"send-error":"closed");try{this.channel.close()}catch{}try{this.pc.close()}catch{}this.onClose?.(this)}}#t(e){if(this.closed||this.channel.readyState!=="open")return!1;try{return this.channel.send(JSON.stringify(e)),!0}catch{return this.close("send-error"),!1}}#e(e){if(this.closed)return;if(typeof e!="string"){let r=this.pending;if(!r)return;if(r.size<0)return this.close("protocol");let s=new Uint8Array(e);if(!s.byteLength||s.byteLength>16384||r.chunks>=this.maxChunks)return this.close("protocol");if(r.chunks+=1,r.received+=s.byteLength,this.bytesIn+=s.byteLength,r.received>r.size)return this.close("protocol");if(r.draining)return;if(r.firstByteAt===null)try{r.firstByteAt=performance.now()}catch{}r.parts.push(s),r.progress?.(r);return}if(e.length>64*1024)return this.close("protocol");let t=JSON.parse(e);if(!(!t||typeof t!="object"))switch(t.t){case"contribution":{if(typeof t.serving!="boolean"||t.rendition!==null&&(typeof t.rendition!="string"||t.rendition.length>2048))return;if(this.contribution={serving:t.serving,rendition:t.rendition,at:Date.now()},t.rendition!==null&&(this.announced.delete(t.rendition),this.announced.size>=8&&this.announced.delete(this.announced.keys().next().value),this.announced.set(t.rendition,Date.now())),!t.serving)this.fetching.clear(),this.renditions.clear();else if(t.rendition!==null){for(let[r,s]of this.renditions)s2e3)return;for(let[r,s]of this.fetching)s<=Date.now()&&this.fetching.delete(r);t.ms===0?this.fetching.delete(t.k):this.contribution.serving&&(this.fetching.has(t.k)||this.fetching.size<24)&&this.fetching.set(t.k,Date.now()+t.ms),this.onScheduleChange?.(this);return}case"have":return this.#s(t);case"want":return this.#d(t);case"cancel":{if(!Number.isSafeInteger(t.id))return;for(let r of this.uploads)r.id===t.id&&(r.cancelled=!0,r.resume?.());return}case"meta":{let r=this.pending;if(!r)return;if(t.id!==r.id)return r.draining?this.close("protocol"):void 0;if(r.size!==-1)return this.close("protocol");if(r.expectedSize!==void 0&&t.size!==r.expectedSize)return this.close("protocol");if(!Number.isSafeInteger(t.size)||t.size<1||t.size>this.maxSegmentBytes)return this.close("protocol");r.size=t.size;return}case"eof":{let r=this.pending;if(!r)return;if(t.id!==r.id)return r.draining?this.close("protocol"):void 0;if(r.cancelled&&r.size>=0)return r.finish(null);if(r.received!==r.size)return this.close("protocol");if(r.draining)return r.finish(null);let s=new Uint8Array(r.size),i=0;for(let o of r.parts)s.set(o,i),i+=o.byteLength;return r.finish(s)}case"none":if(this.pending){if(t.id!==this.pending.id)return this.pending.draining?this.close("protocol"):void 0;if(this.pending.size!==-1)return this.close("protocol");this.pending.finish(null)}return;default:return}}#s(e){let t=s=>Array.isArray(s)?s.filter(i=>typeof i=="string"&&Un.test(i)).slice(0,256):[],r=[];if(Array.isArray(e.keys)){this.have.clear();for(let s of t(e.keys))this.have.add(s);r.push(...this.have)}for(let s of t(e.add)){if(this.have.size>=256)break;this.have.add(s),r.push(s)}for(let s of t(e.del))this.have.delete(s);r.length&&this.onHaveChange?.(this,r)}#d(e){if(!Number.isSafeInteger(e.id)||typeof e.k!="string"||!Un.test(e.k))return;if(this.outboundInFlight>=this.maxQueuedRequests)return this.close("upload-queue");this.outboundInFlight+=1;let t={id:e.id,cancelled:!1};this.uploads.add(t),this.serving=this.serving.then(()=>this.#i(t,e.k)).catch(()=>this.close(this.#r?"upload-drain-timeout":"serve-error")).finally(()=>{this.uploads.delete(t),this.outboundInFlight=Math.max(0,this.outboundInFlight-1)})}async#i(e,t){let{id:r}=e;if(e.cancelled)return this.onUploadCancelled?.(this,0),void this.#t({t:"none",id:r});let s=this.closed?null:await this.onRequest?.(this,t);if(!s)return void this.#t({t:"none",id:r});if(e.cancelled)return this.onUploadCancelled?.(this,s.byteLength),void this.#t({t:"none",id:r});if(!this.#t({t:"meta",id:r,size:s.byteLength}))return;let i=0;for(;i131072&&await this.#c(e),this.closed))return;if(e.cancelled)break;let o=Math.min(i+16384,s.byteLength);this.channel.send(s.subarray(i,o)),i=o}this.bytesOut+=i,this.lastServedAt=Date.now(),i{let s=setTimeout(()=>{i(),this.#r=!0,r(new Error("Peer upload stalled."))},this.drainTimeoutMs),i=()=>{clearTimeout(s),this.channel.removeEventListener("bufferedamountlow",o),this.channel.removeEventListener("close",o),e.resume===o&&delete e.resume},o=()=>{i(),t()};this.channel.addEventListener("bufferedamountlow",o),this.channel.addEventListener("close",o),e.resume=o})}};function Bi(n,e){if(!n.length)return null;let t=[...n].sort((r,s)=>r-s);return t[Math.min(t.length-1,Math.floor(t.length*e))]}var wa=n=>Bi(n,.5),wt=class{constructor(){this.observations=new WeakMap,this.turn=0,this.order=0,this.recentCompletions=[],this.recentFirstBytes=[],this.recentRates=[],this.lastObservedAt=0}observe({firstByteMs:e=null,bytes:t=0,flowMs:r=0,totalFlowMs:s=r}={}){Number.isFinite(e)&&e>=0&&(this.recentFirstBytes.push(Math.min(6e4,e)),this.recentFirstBytes.length>16&&this.recentFirstBytes.shift()),t>=32768&&r>=300&&(this.recentRates.push({rate:Math.min(1e6,t/r),flowMs:Math.max(r,s||0)}),this.recentRates.length>16&&this.recentRates.shift(),this.lastObservedAt=Date.now())}firstByteMs(){return wa(this.recentFirstBytes)}rate(){let e=this.firstByteMs(),t=e===null?[]:this.recentRates.filter(({flowMs:r})=>r>=e*3);return Bi((t.length>=2?t:this.recentRates).map(({rate:r})=>r),.75)}projectMs(e){if(!e)return null;let t=this.firstByteMs(),r=this.rate(),s=[this.minimumMs(e),t!==null&&r?t+e/r:0].filter(Boolean);return s.length?Math.min(...s):null}minimumMs(e){if(!e)return 0;let t=0;for(let{bytes:r,rate:s}of this.recentCompletions)r>=e&&s>t&&(t=s);return t?e/t:0}summary(e){let t=this.observations.get(e);return t?{...t}:{attempts:0,latencyMs:null,throughputBytesPerSecond:null,failureRate:0,consecutiveFailures:0,lastSelected:0}}estimate(e,t){let r=this.summary(e);if(r.latencyMs===null)return null;let s=t&&r.throughputBytesPerSecond?t*1e3/r.throughputBytesPerSecond:0;return Math.max(r.latencyMs,s)}select(e,t,r,s,i=1/0){let o=[...e].filter(f=>!f.closed&&!f.busy&&!r.has(f.pubkey)&&f.have.has(t)&&(this.estimate(f,s)===null||this.estimate(f,s)*1.25+25<=i));if(!o.length)return null;let a=o.filter(f=>!this.observations.get(f)?.attempts),l=o.filter(f=>this.observations.get(f)?.attempts),c=l.filter(f=>this.summary(f).consecutiveFailures===0),u=a.length&&(!c.length||this.turn===0&&i>=100);this.turn=(this.turn+1)%4;let d=u?a:c.length?c:l,p=f=>{let m=this.summary(f);return u?m.lastSelected:(this.estimate(f,s)??1e3)*(1+m.failureRate*4)},g=d.reduce((f,m)=>p(m)a===null?l:a*.75+l*.25,o=Math.min(6e4,Math.max(1,t));s.attempts=Math.min(32,s.attempts+1),s.failureRate=s.failureRate*.75+(r?0:.25),s.consecutiveFailures=r?0:Math.min(32,s.consecutiveFailures+1),r&&(s.latencyMs=i(s.latencyMs,o),s.throughputBytesPerSecond=i(s.throughputBytesPerSecond,Math.min(1e9,r*1e3/o)),this.recentCompletions.push({bytes:r,rate:Math.min(1e6,r/o)}),this.lastObservedAt=Date.now(),this.recentCompletions.length>16&&this.recentCompletions.shift()),this.observations.set(e,s)}};var Cr=class{#r=0;#t=null;#e=-1/0;discard(e){this.#r=0,this.#t=null,Number.isFinite(e)&&(this.#e=Math.max(this.#e,e))}record({freshBytes:e,startAt:t,endAt:r}){if(e===0)return null;if(!Number.isSafeInteger(e)||e<0||!Number.isSafeInteger(this.#r+e)||!Number.isFinite(t)||t<0||!Number.isFinite(r)||rDate.now()){this.clock=e,this.contexts=new Map,this.candidates=new Map,this.window=null,this.counters={checks:0,replacements:0,expired:0,opened:0,verified:0,staleHolder:0,staleBlocked:0,heldMiss:0,rearmed:0,victimUnhelpful:0,victimServing:0,victimConsumer:0,unmetNoHint:0,unmetIneligible:0}}context(e,t){if(!["main","audio"].includes(e))return null;let r=this.contexts.get(e);if(!r||r.rendition!==t)r={mediaType:e,rendition:t,keys:[],lastDemandAt:null,activityAt:this.clock(),spentAt:null,get spent(){return this.spentAt!==null},holders:new Map},this.contexts.set(e,r);else{let s=this.clock();(s=3e4||r.lastDemandAt!==null&&(s=3e4))&&(r.keys=[],r.lastDemandAt=null,r.holders.clear()),r.activityAt=this.clock()}return r}demand(e,t,r){let s=this.context(e,t);if(!s||!er.test(r))return;let i=this.live()&&this.window.context===s?this.window.attempt?.key:null;return s.keys=[...new Set([...i?[i]:[],r,...s.keys])].slice(0,2),s.lastDemandAt=this.clock(),s}hint(e,t,r){!er.test(e)||!Array.isArray(t)||(this.candidates.delete(e),this.candidates.set(e,{pubkey:e,have:[...new Set(t.filter(s=>typeof s=="string"&&er.test(s)))].slice(-8),ticket:ye(r)?r:null,at:this.clock()}),this.candidates.size>64&&this.candidates.delete(this.candidates.keys().next().value))}#r(e){return!!(e&&this.contexts.get(e.mediaType)===e)}holderMiss(e,t,r){if(!this.#r(e)||!er.test(t)||!er.test(r))return!1;let s=e.holders.get(t);return s?s.lastKey===r?!1:(s.misses++,s.lastKey=r,!0):(e.holders.size>=Sa&&e.holders.delete(e.holders.keys().next().value),e.holders.set(t,{firstMissAt:this.clock(),misses:1,lastKey:r}),!0)}holderAhead(e,t){this.holderDelivered(e,t)}holderDelivered(e,t){this.#r(e)&&e.holders.delete(t)}stale(e,t){let r=this.#r(e)?e.holders.get(t):null;return!!r&&r.misses>=va&&this.clock()-r.firstMissAt>=xa}forget(e){for(let t of this.contexts.values())t.holders.delete(e)}spent(e){return e.spentAt!==null}rearm(e,t){if(!this.#r(e)||!this.spent(e))return!1;let r=this.clock();return r=e.activityAt&&t-e.activityAt<3e4&&e.lastDemandAt!==null&&t>=e.lastDemandAt&&t-e.lastDemandAt<3e4}choose(e,t,r){if(this.window?.attempt)return null;let s=this.window?[this.window.context]:[...this.contexts.values()],i=!1,o=!1;for(let a of s){if(!this.current(a)||!t(a)||!r&&this.spent(a)&&!this.window?.vacant)continue;let l=this.hinted(a,e);if(l)return l;this.#t(a)?o||(o=!0,this.counters.unmetIneligible++):i||(i=!0,this.counters.unmetNoHint++)}return null}#t(e){for(let t of this.candidates.values())if(!(this.clock()=6e4)&&e.keys.some(r=>t.have.includes(r)))return!0;return!1}hinted(e,t){for(let r of this.candidates.values()){if(this.clock()=6e4||!t(r))continue;let s=e.keys.find(i=>r.have.includes(i));if(s)return{context:e,candidate:r,key:s}}return null}begin({context:e,candidate:t,key:r}){let s=this.window;if(!s){let o=this.clock();s={context:e,createdAt:o,expiresAt:Math.min(o+15e3,t.at+6e4,e.lastDemandAt+3e4),attempt:null,vacant:!1,victim:null,timer:null},this.window=s}if(s.context!==e||s.attempt||this.clock()>=s.expiresAt)return null;let i={window:s,pubkey:t.pubkey,ticket:t.ticket,key:r,dial:null,negotiation:null};return s.attempt=i,this.counters.checks++,i}valid(e){let t=e?.window,r=this.candidates.get(e?.pubkey);return!!(t&&this.live(t)&&t.attempt===e&&this.current(t.context)&&r&&this.clock()>=r.at&&this.clock()-r.at<6e4&&r.ticket===e.ticket&&r.have.includes(e.key))}replaced(e,t){return!this.valid(e)||this.spent(e.window.context)?!1:(e.window.context.spentAt=this.clock(),e.window.vacant=!0,e.window.victim=t,this.counters.replacements++,!0)}allocated(e,t){e.dial=t,e.window.vacant=!1}abandoned(e){this.window?.attempt===e&&(this.window.attempt=null)}failed(e){let t=this.window?.attempt;!t||t.dial!==e||(t.window.attempt=null,t.window.vacant=t.window.victim!==null)}end(e=this.window){return!e||this.window!==e?!1:(this.window=null,!0)}verified(e){return!e||this.contexts.get(e.mediaType)!==e?!1:(e.spentAt=null,this.counters.verified++,!0)}live(e=this.window){return!!(e&&this.window===e&&this.clock()>=e.createdAt&&this.clock()e+t.keys.length,0),replacementSpent:[...this.contexts.values()].filter(e=>this.spent(e)).length,replacementRearmMs:Ri,opportunityActive:this.live(),remainingMs:this.live()?Math.min(15e3,this.window.expiresAt-this.clock()):0,vacancyReserved:this.reserved(),counters:{...this.counters}}}clear(){this.window=null,this.contexts.clear(),this.candidates.clear()}};function lt(n,e,t){return new Promise((r,s)=>{let i=new AbortController,o=!1,a,l=(u,d,p=!1,g=d)=>{o||(o=!0,clearTimeout(a),e?.removeEventListener("abort",c),p&&i.abort(g),u?r(d):s(d))},c=()=>l(!1,new Error("Operation cancelled."),!0,e.reason);if(e?.aborted)return c();e?.addEventListener("abort",c,{once:!0}),a=setTimeout(()=>l(!1,new Error("Operation cancelled or timed out."),!0),t),Promise.resolve().then(()=>{if(!o)return n(i.signal)}).then(u=>l(!0,u),u=>l(!1,u))})}var Ti=24172,Ea=24173,Aa=24174,zn=/^[0-9a-f]{64}$/u,ka="relayswarm-segment-v1",Ma="relayswarm-segment-v2",Ba="relayswarm-segment-v3",Li={1:ka,2:Ma,3:Ba},Ra=new TextEncoder,Ta=512,vt=new Map;function Nr(n){let e={id:n.id,pubkey:n.pubkey,created_at:n.created_at,kind:n.kind,tags:n.tags,content:n.content,sig:n.sig},t;try{t=Gt(e)}catch{return!1}if(t!==e.id||typeof e.sig!="string")return!1;let r=`${t}:${e.pubkey}:${e.sig}`;return vt.has(r)?(vt.delete(r),vt.set(r,!0),!0):Zt(e)?(vt.size>=Ta&&vt.delete(vt.keys().next().value),vt.set(r,!0),!0):!1}function Pr(n){return Ra.encode(JSON.stringify(n)).length<=16*1024}function ct(n,e){let t=n.tags.filter(r=>r[0]===e);return t.length===1&&t[0].length===2?t[0][1]:null}function Fn(n){return typeof n=="string"&&/^\/media\/[a-z0-9_./-]+$/iu.test(n)&&!n.split("/").includes("..")}function xt(n){return Math.ceil(Math.max(65536,Math.ceil(n/64))/16384)*16384}function _i(n){return n.v===3?3:n.v===2?2:1}function Oi(n){let e=_i(n),t=e>=2;return JSON.stringify({domain:Li[e],v:e,streamEventId:n.streamEventId,swarmId:n.swarmId,key:n.key,rendition:n.rendition,sequence:n.sequence,discontinuity:n.discontinuity,part:n.part,sha256:n.sha256,size:n.size,expiresAt:n.expiresAt,...t?{playlist:n.playlist,mediaType:n.mediaType,encryption:n.encryption}:{},...e===3?{pieceSize:n.pieceSize,pieces:n.pieces}:{}})}function La(n){return JSON.stringify({domain:"relayswarm-commitment-delegation-v1",v:1,streamEventId:n.streamEventId,swarmId:n.swarmId,delegatePubkey:n.delegatePubkey,notBefore:n.notBefore,expiresAt:n.expiresAt,renditions:n.renditions,mediaTypes:n.mediaTypes,allowParts:n.allowParts,maxSegmentBytes:n.maxSegmentBytes})}function _a(n){return JSON.stringify({domain:"relayswarm-commitment-revocation-v1",v:1,streamEventId:n.streamEventId,swarmId:n.swarmId,delegationId:n.delegationId})}function Hr(n){try{return n.kind===30311&&Pr(n)&&Nr(n)&&typeof ct(n,"d")=="string"&&n.tags.some(e=>e.length===3&&e[0]==="relayswarm"&&e[1]==="redistribute"&&e[2]==="1")}catch{return!1}}function Oa(n,{streamEvent:e,swarmId:t,revokedDelegationIds:r=[],delegationRevocations:s=[]},i=Date.now()){try{let o=Math.floor(i/1e3);if(!Hr(e)||!n||!Pr(n)||n.kind!==Ea||n.pubkey!==e.pubkey||!Nr(n)||ct(n,"x")!==t||ct(n,"e")!==e.id||!Number.isSafeInteger(n.created_at)||n.created_at>o+30||!Array.isArray(r)||r.length>256||r.includes(n.id)||!Array.isArray(s)||s.length>256)return null;let a=JSON.parse(n.content);if(n.content!==La(a)||a.domain!=="relayswarm-commitment-delegation-v1"||a.v!==1||a.streamEventId!==e.id||a.swarmId!==t||!zn.test(a.delegatePubkey)||!Number.isSafeInteger(a.notBefore)||a.notBeforeo||!Number.isSafeInteger(a.expiresAt)||a.expiresAt<=o||a.expiresAt<=a.notBefore||a.expiresAt>n.created_at+3600||!Array.isArray(a.renditions)||!a.renditions.length||a.renditions.length>40||new Set(a.renditions).size!==a.renditions.length||a.renditions.some(l=>!(Fn(l)||/^(?:0|[1-9][0-9]{0,3})$/u.test(l)))||!Array.isArray(a.mediaTypes)||!a.mediaTypes.length||a.mediaTypes.length>2||new Set(a.mediaTypes).size!==a.mediaTypes.length||a.mediaTypes.some(l=>!["main","audio"].includes(l))||typeof a.allowParts!="boolean"||!Number.isSafeInteger(a.maxSegmentBytes)||a.maxSegmentBytes<1||a.maxSegmentBytes>16*1024*1024)return null;for(let l of s){if(!l||!Pr(l)||l.kind!==Aa||l.pubkey!==e.pubkey||!Number.isSafeInteger(l.created_at)||l.created_ato+30||!Nr(l)||ct(l,"e")!==n.id||ct(l,"x")!==t)continue;let c=JSON.parse(l.content);if(l.content===_a(c)&&c.domain==="relayswarm-commitment-revocation-v1"&&c.v===1&&c.streamEventId===e.id&&c.swarmId===t&&c.delegationId===n.id)return null}return a}catch{return null}}function Ot(n){try{let e=n.frag.baseurl||n.frag.base?.url;if(typeof e!="string"||e.length>4096)return null;let t=new URL(e);if(!["http:","https:"].includes(t.protocol)||new Set([...t.searchParams.keys()]).size!==[...t.searchParams.keys()].length||t.username||t.password||t.hash||[...t.searchParams].some(([o,a])=>!["_HLS_msn","_HLS_part","_HLS_skip"].includes(o)||!/^(?:[0-9]+|YES|v2)$/u.test(a))||!Fn(t.pathname))return null;let r=n.frag.type??"main";if(!["main","audio"].includes(r))return null;let s=n.frag.decryptdata,i=null;if(s?.method&&s.method!=="NONE"){if(s.method!=="AES-128"||s.keyFormat&&s.keyFormat!=="identity")return null;let o=new URL(s.uri,t);if(o.origin!==t.origin||o.search||o.hash||!Fn(o.pathname)||!s.iv||s.iv.length!==16||Array.from(s.iv).some(a=>!Number.isInteger(a)||a<0||a>255))return null;i={method:"AES-128",keyPath:o.pathname,iv:Array.from(s.iv,a=>a.toString(16).padStart(2,"0")).join(""),keyFormat:"identity"}}return{playlist:t.pathname,mediaType:r,encryption:i}}catch{return null}}function Ii(n,{streamEvent:e,swarmId:t,key:r,context:s,maxSegmentBytes:i,delegation:o,revokedDelegationIds:a,delegationRevocations:l},c=Date.now()){try{let u=Math.floor(c/1e3);if(!Number.isSafeInteger(i)||i<1||i>16*1024*1024||!Hr(e)||!n||n.kind!==Ti||!Pr(n)||!Number.isSafeInteger(n.created_at)||n.created_at>u+30||n.created_at=2;if(n.content!==Oi(d)||d.domain!==Li[p]||![1,2,3].includes(d.v)||d.streamEventId!==e.id||d.swarmId!==t||d.key!==r||d.sequence!==s.frag.sn||d.discontinuity!==(s.frag.cc??0)||d.part!==(s.part?.index??null)||!Number.isSafeInteger(d.sequence)||d.sequence<0||!Number.isSafeInteger(d.discontinuity)||d.discontinuity<0||d.part!==null&&(!Number.isSafeInteger(d.part)||d.part<0)||!zn.test(d.sha256)||!Number.isSafeInteger(d.size)||d.size<1||d.size>i||!Number.isSafeInteger(d.expiresAt)||d.expiresAt<=u||d.expiresAt>u+300||p===3&&(d.pieceSize!==xt(d.size)||!Array.isArray(d.pieces)||d.pieces.length!==Math.ceil(d.size/d.pieceSize)||d.pieces.some(f=>typeof f!="string"||!zn.test(f))))return null;if(g){let f=Ot(s);if(!f||d.rendition!==f.playlist||d.playlist!==f.playlist||d.mediaType!==f.mediaType||JSON.stringify(d.encryption)!==JSON.stringify(f.encryption))return null}else if(d.rendition!==String(s.frag.level)||s.frag.type&&s.frag.type!=="main"||s.frag.decryptdata?.method&&s.frag.decryptdata.method!=="NONE")return null;if(n.pubkey!==e.pubkey){let f=Oa(o,{streamEvent:e,swarmId:t,revokedDelegationIds:a,delegationRevocations:l},c);if(!f||n.pubkey!==f.delegatePubkey||ct(n,"delegation")!==o.id||n.created_atf.expiresAt||!f.renditions.includes(d.rendition)||!f.mediaTypes.includes(g?d.mediaType:"main")||d.part!==null&&!f.allowParts||d.size>f.maxSegmentBytes)return null}return d}catch{return null}}var Ci=new TextEncoder,Ia=new TextDecoder;function Ni(n,e,t){let r=e.byteLength,s=n.rs_alloc(r);try{return new Uint8Array(n.memory.buffer,s,r).set(e),t(s,r)}finally{n.rs_free(s,r)}}var Ca=(n,e)=>new Uint8Array(n.memory.buffer,n.rs_result_ptr(),e);function Pi(n,{size:e,sha256:t,pieces:r,deadline:s,maxHolders:i,originReserveMs:o,peerOnly:a=!1},l,c){if(l()||!Na.every(u=>typeof n[u]=="function")||typeof a!="boolean")return null;if(a)try{if(typeof n.rs_xfer_capabilities!="function"||!(n.rs_xfer_capabilities()&2))return null}catch{return null}try{let u=Ni(n,Ci.encode(JSON.stringify({sha256:t,pieces:r,...a?{peerOnly:!0}:{}})),(d,p)=>n.rs_xfer_new(e,s,i,o,d,p));return u?new jn(n,u,l,c,a):null}catch(u){return c(u),null}}var Na=["rs_xfer_new","rs_xfer_call","rs_xfer_free"],tr={start:0,delivered:1,failed:2,tick:3,state:4,progress:5},jn=class{#r;#t;#e;#s;#d;constructor(e,t,r,s,i=!1){this.#r=e,this.#t=t,this.#e=r,this.#s=s,this.#d=i}start(e,{peers:t,origin:r,sharedFirstByteMs:s=null,sharedRate:i=null,probePeers:o=[]}){let a=!1;try{a=typeof this.#r.rs_xfer_capabilities=="function"&&!!(this.#r.rs_xfer_capabilities()&1)}catch{}let l=new Set(o),c=a?t:t.filter(([u])=>!l.has(u));return this.#i(tr.start,e,-1,0,0,Ci.encode(JSON.stringify({peers:c,origin:this.#d?null:r,sharedFirstByteMs:s,sharedRate:i,...a?{probePeers:o}:{}})))}delivered(e,t,r,s){return this.#i(tr.delivered,e,t,r.start,r.end,s)}failed(e,t){return this.#i(tr.failed,e,t,0,0,qn)}tick(e){return this.#i(tr.tick,e,-1,0,0,qn)}progress(e,t,r){return this.#i(tr.progress,e,t,r,0,qn)}free(){if(this.#t===null)return;let e=this.#t;if(this.#t=null,!this.#e())try{this.#r.rs_xfer_free(e)}catch(t){this.#s(t)}}#i(e,t,r,s,i,o){if(this.#t===null||this.#e())return null;let a=this.#r;try{let l=Ni(a,o,(f,m)=>a.rs_xfer_call(this.#t,e,Math.floor(t),r==="origin"?-1:r,s,i,f,m));if(l<4)throw new Error(`Core transfer refused operation ${e}.`);let c=Ca(a,l),u=new DataView(c.buffer,c.byteOffset,l).getUint32(0,!0),d=JSON.parse(Ia.decode(c.subarray(4,4+u))),p=l>4+u?c.slice(4+u):null;return{commands:d.c.map(f=>f.p?{...f,range:{start:f.p[0],end:f.p[1]}}:f),next:d.next,late:d.late,finished:d.finished,verified:d.verified??null,bytes:p}}catch(l){return this.#s(l),null}}},qn=new Uint8Array(0);var Se={text:0,binary:1,request:2,abort:3,close:4,tick:5,serve:6,bufferedLow:7,sendHave:8,sendHaveChange:9,sendContribution:10,sendFetching:11,state:12,sets:13,requestRange:14,serveRange:15},He={sendText:1,sendBinary:2,closed:3,report:4,resolved:5,haveChanged:6,scheduleChanged:7,serveRequest:8,uploadCancelled:9,progress:10,serveRange:11},Pa=128*1024,Ha=32*1024,Da=new Set(["host","host-stop","admission","rotation","integrity","request-timeout","request-abort","native-failed","native-closed","native-disconnected","channel-close","channel-error","protocol","send-error","serve-error","upload-queue","upload-drain-timeout"]),ht=new TextEncoder,It=new TextDecoder,Wn=new Uint8Array(0),Kn=()=>{try{return globalThis.performance.now()}catch{return null}},Hi=n=>{let e=Math.trunc(Math.max(1,n));return e>=1&&e<=2**31-1?e:1},Dr=class n{get supportsRanges(){return!this.closed}static ABANDON_REASON=at.ABANDON_REASON;#r;#t;#e=-1;#s=null;#d=null;#i=0;#c=!1;#o=!1;#n=new Map;#h=null;#M=!1;#B=0;constructor({pubkey:e,pc:t,channel:r,maxSegmentBytes:s,onRequest:i,onHaveChange:o,onScheduleChange:a,onClose:l,onUploadCancelled:c,maxQueuedRequests:u=4,drainTimeoutMs:d=3e3},p){this.pubkey=e,this.pc=t,this.channel=r,this.maxSegmentBytes=s,this.onRequest=i,this.onHaveChange=o,this.onScheduleChange=a,this.onClose=l,this.onUploadCancelled=c,this.maxQueuedRequests=u,this.drainTimeoutMs=d,this.contribution={serving:!1,rendition:null,at:0},this.fetching=new Map,this.renditions=new Map,this.have=new Set,this.announced=new Map,this.closed=!1,this.closeReason=void 0,this.openedAt=Date.now(),this.lastServedAt=0,this.lastDeliveredAt=0,this.outboundInFlight=0,this.bytesIn=0,this.bytesOut=0,this.#r=p,this.#i=this.openedAt,this.#t=p.newLink(s,u,d,this.#l(),this.openedAt),p.links.add(this),r.binaryType="arraybuffer",r.bufferedAmountLowThreshold=Ha,r.addEventListener("message",g=>{if(this.closed)return;let{data:f}=g;typeof f=="string"?this.#a(Se.text,{bytes:ht.encode(f)}):this.#a(Se.binary,{bytes:f instanceof ArrayBuffer?new Uint8Array(f):ArrayBuffer.isView(f)?new Uint8Array(f.buffer,f.byteOffset,f.byteLength):Wn})}),r.addEventListener("close",()=>this.close("channel-close")),r.addEventListener("error",()=>this.close("channel-error")),r.addEventListener("bufferedamountlow",()=>{this.closed||this.#a(Se.bufferedLow,{a:this.#R()})}),t.addEventListener("connectionstatechange",()=>{let g=t.connectionState;["failed","closed","disconnected"].includes(g)&&this.close(`native-${g}`)})}get kind(){return"wasm"}get busy(){return this.#c}get transferring(){return this.#o}get lastUsefulAt(){return Math.max(this.lastDeliveredAt,this.lastServedAt,this.openedAt)}sendHave(e){this.closed||this.#a(Se.sendHave,{bytes:ht.encode(JSON.stringify([...e]))})}sendHaveChange(e=[],t=[]){this.closed||this.#a(Se.sendHaveChange,{bytes:ht.encode(JSON.stringify({add:[...e],del:[...t]}))})}sendContribution(e,t){this.closed||this.#a(Se.sendContribution,{a:e?1:0,bytes:ht.encode(JSON.stringify(typeof t=="string"?t:null))})}sendFetching(e,t=0){this.closed||this.#a(Se.sendFetching,{a:t,bytes:ht.encode(String(e))})}request(e,t,{signal:r,expectedSize:s,onResult:i,onProgress:o,range:a}={}){let l=Kn(),c=!1,u=(p,g=null)=>{if(!c&&(c=!0,typeof i=="function"))try{let f=null;if(Number.isFinite(l)){let v=Kn();Number.isFinite(v)&&(f=v-l)}let m=g?.receivedBytes??0,b=Number.isFinite(d?.firstByteAt)&&Number.isFinite(l)?d.firstByteAt-l:null;i({outcome:p,elapsedMs:Number.isFinite(f)&&f>=0?f:null,timeoutMs:Number.isFinite(t)&&t>=0?t:null,expectedBytes:Number.isSafeInteger(s)&&s>=0?s:null,receivedBytes:Number.isSafeInteger(m)&&m>=0?m:null,firstByteMs:Number.isFinite(b)&&b>=0?b:null,metadataReceived:g?.metadataReceived===!0,draining:g?.draining===!0,closeReason:Da.has(this.closeReason)?this.closeReason:null})}catch{}},d=null;if(this.closed||this.#c||r?.aborted){let p=Promise.resolve(null);return u(this.closed?"closed":this.#c?"busy":"abort"),p}return new Promise(p=>{let g=()=>{d.id!==null&&!this.closed&&this.#a(Se.abort,{a:d.id,b:r?.reason===n.ABANDON_REASON?1:0})};d={id:null,firstByteAt:null,settled:!1,report:u,onProgress:o,startedAt:l,settle:m=>{d.settled||(d.settled=!0,r?.removeEventListener("abort",g),p(m))}};let f=s===void 0?NaN:Number.isSafeInteger(s)&&s>=0?s:-1;this.#h=d;try{a?this.#a(Se.requestRange,{a:Hi(t),b:a.objectSize,bytes:ht.encode(JSON.stringify([String(e),a.start,a.end]))}):this.#a(Se.request,{a:Hi(t),b:f,bytes:ht.encode(String(e))})}finally{this.#h=null}if(d.id===null){d.settle(null),u("closed");return}d.settled||r?.addEventListener("abort",g,{once:!0})})}close(e="host"){if(!this.closed){if(this.#t===null)return this.#b("host");this.#a(Se.close,{bytes:ht.encode(typeof e=="string"?e:"host")})}}die(){this.#b("host")}#b(e){if(!this.closed){this.closed=!0,this.closeReason=e,this.#t=null,this.#r.links.delete(this),this.#I(),this.fetching.clear(),this.renditions.clear(),this.announced.clear(),this.#c=!1,this.#o=!1;for(let t of this.#n.values())t.settle(null),t.report("closed");this.#n.clear();try{this.channel.close()}catch{}try{this.pc.close()}catch{}this.onClose?.(this)}}#S(){try{return this.channel.readyState==="open"}catch{return!1}}#l(){try{return this.channel.ordered===!0&&this.channel.maxRetransmits===null&&this.channel.maxPacketLifeTime===null}catch{return!1}}#f(){return this.#i=Math.max(this.#i,Date.now()),this.#i}#a(e,{a:t=0,b:r=0,bytes:s=Wn,now:i=this.#f()}={}){if(this.#t===null)return;let o=this.#r.call(this.#t,e,i,(this.#S()?1:0)|(this.#l()?2:0),t,r,s);o&&this.#k(o)}#k({header:e,events:t}){let[r,s,i,o,a,l,c,u,d,p,g,f,m]=e;this.closed=s===1,this.#c=i===1,this.#o=o===1,this.outboundInFlight=a,this.bytesIn=l,this.bytesOut=c,this.openedAt=u,this.lastServedAt=d,this.lastDeliveredAt=p,!Number.isNaN(f)&&this.#h&&(this.#h.id=f,this.#n.set(f,this.#h)),r!==this.#e&&this.#w(r),this.closed&&this.announced.clear();let b=++this.#B;for(let v of t)this.#O(v);if(b===this.#B&&this.#t!==null&&(this.#Y(g),m===1&&this.#R()<=Pa))return this.#a(Se.bufferedLow,{a:this.#R()});this.closed&&!this.#o&&this.#t!==null&&(this.#r.free(this.#t),this.#t=null,this.#r.links.delete(this),this.#I())}#w(e){let t=this.#r.sets(this.#t);if(t){this.#e=e,this.have.clear();for(let r of t.have)this.have.add(r);this.fetching.clear();for(let[r,s]of t.fetching)this.fetching.set(r,s);this.renditions.clear();for(let[r,s]of t.renditions)this.renditions.set(r,s);(t.serving!==this.contribution.serving||t.rendition!==this.contribution.rendition||t.at!==this.contribution.at)&&(this.contribution={serving:t.serving,rendition:t.rendition,at:t.at},t.rendition!==null&&(this.announced.delete(t.rendition),this.announced.size>=8&&this.announced.delete(this.announced.keys().next().value),this.announced.set(t.rendition,t.at))),t.closeReason!==null&&(this.closeReason=t.closeReason)}}#O({tag:e,payload:t,id:r}){let s=i=>new DataView(t.buffer,t.byteOffset,t.byteLength).getFloat64(i*8,!0);switch(e){case He.sendText:{if(this.#M)return;let i=It.decode(t);try{this.channel.send(i)}catch{this.#M=!0,this.close("send-error")}return}case He.sendBinary:{if(this.#M)return;try{this.channel.send(t)}catch{this.#M=!0,this.close("serve-error")}return}case He.closed:{this.closeReason=It.decode(t),this.#I();try{this.channel.close()}catch{}try{this.pc.close()}catch{}this.onClose?.(this);return}case He.report:{let i=JSON.parse(It.decode(t)),o=i.id===null?this.#h:this.#n.get(i.id);if(!o)return;o.report(i.outcome,i),o.settled&&i.id!==null&&this.#n.delete(i.id);return}case He.resolved:{let i=Number.isNaN(r)?this.#h:this.#n.get(r);if(!i)return;i.settle(t);return}case He.haveChanged:{let i=JSON.parse(It.decode(t));this.onHaveChange?.(this,i);return}case He.scheduleChanged:{this.onScheduleChange?.(this);return}case He.serveRequest:case He.serveRange:{let i,o;if(e===He.serveRange){let[a,l,c]=JSON.parse(It.decode(t));i=a,o={start:l,end:c}}else i=It.decode(t);Promise.resolve().then(()=>this.closed?null:o?this.onRequest?.(this,i,o):this.onRequest?.(this,i)).then(a=>this.#v(a,o),()=>{this.close("serve-error"),this.#v(null)});return}case He.uploadCancelled:{this.onUploadCancelled?.(this,s(0));return}case He.progress:{let i=s(0),o=s(1);for(let a of this.#n.values())if(!a.settled&&(a.firstByteAt===null&&(a.firstByteAt=Kn()),typeof a.onProgress=="function"))try{a.onProgress(i,o,Number.isFinite(a.startedAt)?a.firstByteAt-a.startedAt:null)}catch{}return}default:throw new Error(`Unknown core link event ${e}.`)}}#R(){try{return Math.max(0,Number(this.channel.bufferedAmount)||0)}catch{return 0}}#v(e,t){if(this.#t===null)return;let r=this.#R(),s=e?e instanceof Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e instanceof ArrayBuffer?new Uint8Array(e):null:null;if(e&&!s)return this.close("serve-error"),this.#a(Se.serve,{a:0,b:r});if(s&&t&&this.#r.rangeUploads){let i=s.byteLength,o=xt(i);return i<1||i>this.maxSegmentBytes||!Number.isSafeInteger(t.start)||!Number.isSafeInteger(t.end)||t.start<0||t.start>=t.end||t.end>Math.ceil(i/o)?this.#a(Se.serve,{a:0,b:r}):this.#a(Se.serveRange,{a:i,b:r,bytes:s.subarray(t.start*o,Math.min(i,t.end*o))})}this.#a(Se.serve,{a:s?1:0,b:r,bytes:s??Wn})}#Y(e){if(Number.isNaN(e))return this.#I();this.#s!==null&&this.#d===e||(this.#I(),this.#d=e,this.#s=globalThis.setTimeout(()=>{this.#s=null,this.#d=null,this.#i=Math.max(this.#i,e),this.#a(Se.tick)},Math.max(0,e-this.#f())))}#I(){this.#s!==null&&globalThis.clearTimeout(this.#s),this.#s=null,this.#d=null}};var Ua=/^[0-9a-f]{64}$/u,ce={context:0,demand:1,hint:2,holderMiss:3,holderAhead:4,stale:5,forget:6,current:7,candidates:8,choose:9,hinted:10,begin:11,valid:12,replaced:13,allocated:14,abandoned:15,failed:16,end:17,verified:18,live:19,reserved:20,suppresses:21,snapshot:22,clear:23,rearm:24},za=6e4,Fa=2e4,qa=new Set([ce.stale,ce.current,ce.valid,ce.live,ce.reserved,ce.suppresses]),rr=class extends Error{constructor(e){super("Core discovery failed.",{cause:e})}},Ur=class{#r;#t;#e=null;#s=new Map;#d=new Map;#i=new WeakMap;#c=null;#o=null;#n=new WeakMap;#h=new WeakMap;#M=new Map;#B=1;#b=null;#S=null;constructor(e,t,r=()=>Date.now()){this.#r=e,this.#t=t,this.clock=r,this.counters={checks:0,replacements:0,expired:0,opened:0,verified:0,staleHolder:0,staleBlocked:0,heldMiss:0,rearmed:0,victimUnhelpful:0,victimServing:0,victimConsumer:0,unmetNoHint:0,unmetIneligible:0}}get kind(){return this.#e?"js":"wasm"}get contexts(){return this.#e?this.#e.contexts:this.#s}get window(){return this.#e?this.#e.window:this.#c}get candidates(){return this.#e?this.#e.candidates:new Map(this.#f(ce.candidates,[]).map(e=>[e.pubkey,e]))}retire(){this.#e||(this.#S=null,this.#e=new _t(this.clock),this.#e.counters=this.counters)}#l(e,t){if(this.#e)return t(this.#e);try{return e()}catch(r){if(!(r instanceof rr))throw r;this.retire();try{this.#t?.(r.cause)}catch{}return t(this.#e)}}#f(e,t){try{let r=this.#r(e,this.clock(),t);if(e===ce.candidates)return r.map(([s,i,o,a])=>({pubkey:s,have:i,ticket:o,at:a}));if(qa.has(e)&&typeof r!="boolean")throw new TypeError(`Core discovery answered operation ${e} with ${typeof r}.`);return r}catch(r){throw new rr(r)}}#a(e,t){try{let{r,s}=this.#r(e,this.clock(),t);return this.#k(s),r}catch(r){throw new rr(r)}}#k({c:e,w:t,n:r}){let s=new Map;this.#s=new Map;for(let i of e){let o=this.#d.get(i.id);o||(o={mediaType:i.mediaType,rendition:i.rendition,keys:[],lastDemandAt:null,activityAt:0,spent:!1},this.#i.set(o,i.id)),(o.keys.length!==i.keys.length||o.keys.some((a,l)=>a!==i.keys[l]))&&(o.keys=i.keys),Object.assign(o,{lastDemandAt:i.lastDemandAt,activityAt:i.activityAt,spent:i.spent,spentAt:i.spentAt}),s.set(i.id,o),this.#s.set(i.mediaType,o)}if(!t)this.#c=null,this.#o=null;else{let i=s.get(t.context)??this.#d.get(t.context);i&&s.set(t.context,i),this.#o!==t.id&&(this.#c={context:i,createdAt:t.createdAt,expiresAt:t.expiresAt,attempt:null,vacant:!1,victim:null,timer:null},this.#o=t.id);let o=this.#c;Object.assign(o,{context:i,expiresAt:t.expiresAt,vacant:t.vacant,victim:t.victim}),t.attempt?(!o.attempt||this.#n.get(o.attempt)!==t.attempt.id)&&(o.attempt={window:o,pubkey:t.attempt.pubkey,ticket:t.attempt.ticket,key:t.attempt.key,dial:null,negotiation:null},this.#n.set(o.attempt,t.attempt.id)):o.attempt=null}this.#d=s,[this.counters.checks,this.counters.replacements,this.counters.verified,this.counters.rearmed,this.counters.unmetNoHint,this.counters.unmetIneligible]=r}#w(e){return e?this.#i.get(e)??null:null}#O(e,t){let s=e===null||typeof e!="object"&&typeof e!="function"?this.#M:this.#h,i=s.get(e);return i===void 0&&t&&s.set(e,i=this.#B++),i}#R(e){let t=this.clock();return this.#S??=this.#f(ce.candidates,[]),this.#S.filter(r=>t>=r.at&&t-r.atr.pubkey)}#v(e){if(!e)return this.#b=null;let[t,r,s,i]=e.candidate,o=this.#d.get(e.context);return this.#b=o?{context:o,candidate:{pubkey:t,have:r,ticket:s,at:i},key:e.key}:null}context(e,t){return e!=="main"&&e!=="audio"?null:this.#l(()=>{let r=this.#a(ce.context,[e,String(t)]);return this.#d.get(r)??null},r=>r.context(e,t))}demand(e,t,r){return this.#l(()=>{if(typeof r!="string"){this.context(e,t);return}if(e!=="main"&&e!=="audio")return;let s=this.#a(ce.demand,[e,String(t),r]);return this.#d.get(s)??void 0},s=>s.demand(e,t,r))}hint(e,t,r){typeof e!="string"||!Ua.test(e)||!Array.isArray(t)||this.#l(()=>{this.#S=null,this.#f(ce.hint,[e,t.filter(s=>typeof s=="string"),ye(r)?r:null])},s=>s.hint(e,t,r))}holderMiss(e,t,r){if(!(typeof t!="string"||typeof r!="string"))return this.#l(()=>this.#f(ce.holderMiss,[this.#w(e),t,r]),s=>s.holderMiss(e,t,r))}holderDelivered(e,t){this.holderAhead(e,t)}spent(e){return this.#e?this.#e.spent(e):e?.spentAt!==null&&e?.spentAt!==void 0}rearm(e,t){return this.#l(()=>{let r=this.#w(e),s=this.clock();return r===null||!this.spent(e)||sr.rearm(e,t))}holderAhead(e,t){typeof t=="string"&&this.#l(()=>{this.#f(ce.holderAhead,[this.#w(e),t])},r=>r.holderAhead(e,t))}stale(e,t){return typeof t!="string"?!1:this.#l(()=>this.#f(ce.stale,[this.#w(e),t]),r=>r.stale(e,t))}forget(e){typeof e=="string"&&this.#l(()=>{this.#f(ce.forget,[e])},t=>t.forget(e))}current(e){return this.#l(()=>this.#w(e)!==null&&this.#f(ce.current,[this.#w(e)]),t=>t.current(e))}choose(e,t,r){return this.#l(()=>{if(this.#c?.attempt)return this.#b=null;let i=(this.#c?[this.#c.context]:[...this.#s.values()]).filter(o=>this.#f(ce.current,[this.#w(o)])&&t(o)).map(o=>o.mediaType);return i.length===0?this.#b=null:this.#v(this.#a(ce.choose,[this.#R(e),i,!!r]))},s=>s.choose(e,t,r))}hinted(e,t){return this.#l(()=>{let r=this.#w(e);return r===null?this.#b=null:this.#v(this.#f(ce.hinted,[r,this.#R(t)]))},r=>r.hinted(e,t))}begin(e){return this.#l(()=>!e||e!==this.#b?null:(this.#b=null,this.#a(ce.begin,[])===null?null:this.#c?.attempt??null),t=>t.begin(e))}valid(e){return this.#l(()=>{let t=e?this.#n.get(e):void 0;return t!==void 0&&this.#f(ce.valid,[t])},t=>t.valid(e))}replaced(e,t){return this.#l(()=>{let r=e?this.#n.get(e):void 0;return r!==void 0&&this.#a(ce.replaced,[r,typeof t=="string"?t:null])},r=>r.replaced(e,t))}allocated(e,t){this.#l(()=>{e.dial=t,e.window.vacant=!1;let r=this.#n.get(e);r!==void 0&&this.#a(ce.allocated,[r,this.#O(t,!0)])},r=>r.allocated(e,t))}abandoned(e){this.#l(()=>{let t=e?this.#n.get(e):void 0;t!==void 0&&this.#a(ce.abandoned,[t])},t=>t.abandoned(e))}failed(e){this.#l(()=>{let t=this.#O(e,!1);t!==void 0&&this.#a(ce.failed,[t])},t=>t.failed(e))}end(e=this.window){return this.#l(()=>!!e&&e===this.#c&&this.#a(ce.end,[]),t=>t.end(e))}verified(e){return this.#l(()=>{let t=this.#w(e);return t!==null&&this.#s.get(e.mediaType)===e&&this.#a(ce.verified,[t])},t=>t.verified(e))}live(e=this.window){return this.#l(()=>!!e&&e===this.#c&&this.#f(ce.live,[]),t=>t.live(e))}reserved(){return this.#l(()=>this.#f(ce.reserved,[]),e=>e.reserved())}suppresses(e){return typeof e!="string"?!1:this.#l(()=>this.#f(ce.suppresses,[e]),t=>t.suppresses(e))}snapshot(){return this.#l(()=>({...this.#f(ce.snapshot,[]),counters:{...this.counters}}),e=>e.snapshot())}clear(){this.#l(()=>{this.#b=null,this.#S=null,this.#a(ce.clear,[])},e=>e.clear())}};var ja=0,Wa=1,Ka=2,Va=3,Di=new TextEncoder,Vn=new TextDecoder;function $a(n){return{sequence:n.frag.sn??null,discontinuity:n.frag.cc??0,part:n.part?.index??null,level:String(n.frag.level),fragType:n.frag.type??null,decryptMethod:n.frag.decryptdata?.method??null,media:Ot(n)}}async function Ga(n){if(n instanceof WebAssembly.Module)return{instance:await WebAssembly.instantiate(n,{}),module:n};if(n instanceof ArrayBuffer||ArrayBuffer.isView(n))return WebAssembly.instantiate(n,{});let e=n instanceof URL?n.href:n;if(typeof e!="string")throw new TypeError("coreWasm must be a URL, bytes or a WebAssembly.Module.");let t=await fetch(e,{credentials:"same-origin"});if(!t.ok)throw new Error(`Core module unavailable (${t.status}).`);if(typeof WebAssembly.instantiateStreaming=="function")try{return await WebAssembly.instantiateStreaming(t.clone(),{})}catch{}return WebAssembly.instantiate(await t.arrayBuffer(),{})}var Ya=["rs_sel_observe","rs_sel_record","rs_sel_mark","rs_sel_forget","rs_sel_select","rs_sel_state","rs_sel_project","rs_sel_minimum","rs_sel_estimate","rs_sel_summary","rs_link_new","rs_link_free","rs_link_call","rs_disc_call"],Ui=13,Za=15,$n=13,Fi=$n*8,Xa=5,Ct=n=>Number.isNaN(n)?null:n,zi=(n,e)=>new Float64Array(n.memory.buffer,e,6);function zr(n,e,t){let r=e.byteLength,s=n.rs_alloc(r);try{return new Uint8Array(n.memory.buffer,s,r).set(e),t(s,r)}finally{n.rs_free(s,r)}}var Fr=(n,e)=>new Uint8Array(n.memory.buffer,n.rs_result_ptr(),e);function Ja(n,e){let t=Fr(n,e),r=new DataView(t.buffer,t.byteOffset,e),s=new Array($n);for(let o=0;o<$n;o++)s[o]=r.getFloat64(o*8,!0);let i=[];for(let o=Fi;oe)throw new Error("Core link frame has a truncated resolution.");i.push({tag:a,id:r.getFloat64(l,!0),payload:t[l+8]===1?t.slice(l+9,c):null})}return{header:s,events:i}}var Gn=class{#r;#t;#e=null;#s=new WeakMap;#d=0;constructor(e,t){this.#r=e,this.#t=t}get kind(){return this.#e?"js":"wasm"}retire(){this.#e??=new wt}#i(e,t){if(this.#e)return t(this.#e);try{return e(this.#r)}catch(r){return this.#e=new wt,this.#t?.(r),t(this.#e)}}#c(e){let t=this.#s.get(e);return t===void 0&&this.#s.set(e,t=this.#d++),t}#o(e){return this.#i(t=>zi(t,t.rs_sel_state())[e],t=>[t.firstByteMs(),t.rate(),t.lastObservedAt,t.turn,t.order][e]??NaN)}get lastObservedAt(){return this.#o(2)}get turn(){return this.#o(3)}get order(){return this.#o(4)}firstByteMs(){return Ct(this.#o(0))}rate(){return Ct(this.#o(1))}observe({firstByteMs:e=null,bytes:t=0,flowMs:r=0,totalFlowMs:s=r}={}){this.#i(i=>i.rs_sel_observe(Date.now(),Number.isFinite(e)?e:NaN,t,r,s||0),i=>i.observe({firstByteMs:e,bytes:t,flowMs:r,totalFlowMs:s}))}record(e,t,r=0){this.#i(s=>s.rs_sel_record(Date.now(),this.#c(e),t,r),s=>s.record(e,t,r))}markSelected(e){this.#i(t=>t.rs_sel_mark(this.#c(e)),t=>t.markSelected(e))}forget(e){let t=this.#s.get(e);this.#i(r=>{t!==void 0&&r.rs_sel_forget(t)},r=>r.forget(e))}projectMs(e){return this.#i(t=>Ct(t.rs_sel_project(e)),t=>t.projectMs(e))}minimumMs(e){return this.#i(t=>t.rs_sel_minimum(e),t=>t.minimumMs(e))}estimate(e,t){return this.#i(r=>Ct(r.rs_sel_estimate(this.#c(e),t)),r=>r.estimate(e,t))}summary(e){return this.#i(t=>{let[r,s,i,o,a,l]=zi(t,t.rs_sel_summary(this.#c(e)));return{attempts:r,latencyMs:Ct(s),throughputBytesPerSecond:Ct(i),failureRate:o,consecutiveFailures:a,lastSelected:l}},t=>t.summary(e))}select(e,t,r,s,i=1/0){return this.#i(o=>{let a=[...e].filter(d=>!d.closed&&!d.busy&&!r.has(d.pubkey)&&d.have.has(t)),l=a.map(d=>this.#c(d)),c=l.length*4,u=o.rs_alloc(c);try{let d=new DataView(o.memory.buffer,u,c);l.forEach((g,f)=>d.setUint32(f*4,g,!0));let p=o.rs_sel_select(u,l.length,s,i);return p<0?null:a[l.indexOf(p)]}finally{o.rs_free(u,c)}},o=>o.select(e,t,r,s,i))}};async function qi(n,{onFailure:e}={}){let{instance:t,module:r}=await Ga(n),s=t.exports;for(let m of["memory","rs_alloc","rs_free","rs_call","rs_result_ptr",...Ya])if(!s[m])throw new Error(`Core module lacks ${m}.`);let i=!1,o=null,a=null,l=()=>{if(!i){i=!0,o?.retire(),a?.retire();for(let m of[...u.links])m.die()}},c=m=>{if(!i){l();try{e?.(m)}catch{}}},u={links:new Set,rangeUploads:typeof s.rs_link_serve_range=="function",newLink(m,b,v,w,T){if(i)throw new Error("The core has been retired.");return s.rs_link_new(m,b,v,w?1:0,T)},free(m){if(!i)try{s.rs_link_free(m)}catch(b){c(b)}},call(m,b,v,w,T,O,K){if(i)return null;try{let A=zr(s,K,(k,W)=>b===Za&&u.rangeUploads?s.rs_link_serve_range(m,v,w,T,O,k,W):s.rs_link_call(m,b,v,w,T,O,k,W));if(A<0||As.rs_link_call(m,Ui,0,0,0,0,v,w));if(b<0)throw new Error(`Core link ${m} refused operation ${Ui}.`);return JSON.parse(Vn.decode(Fr(s,b)))}catch(b){return c(b),null}}};function d(m,b){let v;try{v=Di.encode(JSON.stringify(b))}catch{return null}let w=zr(s,v,(T,O)=>s.rs_call(m,T,O));return w<0?null:JSON.parse(Vn.decode(Fr(s,w)))}function p(m,b,v){if(i)throw new Error("The core has been retired.");let w=Di.encode(JSON.stringify(v)),T=zr(s,w,(O,K)=>s.rs_disc_call(m,b,O,K));if(T<0)throw new Error(`Core discovery refused operation ${m}.`);return JSON.parse(Vn.decode(Fr(s,T)))}let g=({streamEvent:m,swarmId:b,revokedDelegationIds:v=[],delegationRevocations:w=[]})=>({streamEvent:m,swarmId:b,revokedDelegationIds:v,delegationRevocations:w}),f=Object.freeze({kind:"wasm",validStreamAuthorisation:m=>d(ja,[m])===!0,verifyCommitmentDelegation:(m,b,v=Date.now())=>d(Wa,[m??null,g(b),v]),verifySegmentCommitment(m,b,v=Date.now()){let w;try{w=$a(b.context)}catch{return null}return d(Ka,[m??null,{...g(b),key:b.key,context:w,maxSegmentBytes:b.maxSegmentBytes,delegation:b.delegation??null},v])}});return Object.freeze({module:r,verifier:f,playerHint(m){if(i)return null;try{return d(Va,m)}catch(b){return c(b),null}},retire:l,get retired(){return i},peerSelection(){if(o)throw new Error("This core instance already has a peer selection.");return o=new Gn(s,c)},neighbourDiscovery(m){if(a)throw new Error("This core instance already has a neighbour discovery.");if(i)throw new Error("The core has been retired.");return a=new Ur(p,c,m)},peerLink(m){return new Dr(m,u)},transfer(m){return Pi(s,m,()=>i,c)}})}var Qa=new Uint8Array(0);var el=Object.freeze({maxTransfers:2,maxSegmentBytes:16777216,maxActiveBytes:33554432,maxPending:32,maxPendingBytes:33554432,initTimeoutMs:5e3,operationTimeoutMs:5e3}),tl=Object.freeze({maxTransfers:4,maxSegmentBytes:32*1048576,maxActiveBytes:64*1048576,maxPending:128,maxPendingBytes:64*1048576,initTimeoutMs:3e4,operationTimeoutMs:3e4}),ji=n=>typeof n=="string"&&n.length===64&&/^[a-f0-9]{64}$/.test(n),qe=n=>Number.isSafeInteger(n)&&n>=0,sr=n=>Number.isFinite(n)&&n>=0&&n<=Number.MAX_SAFE_INTEGER,nr=n=>n===null||sr(n),rl=(n,e)=>n&&Array.isArray(n.commands)&&n.commands.length<=1024&&n.commands.every(t=>t&&["request","origin","cancel","abandon","ban","deliver","fail"].includes(t.t))&&(n.next===null||sr(n.next))&&typeof n.late=="boolean"&&typeof n.finished=="boolean"&&(n.verified===null||qe(n.verified)&&n.verified<=e)&&(n.bytes===null||n.bytes instanceof Uint8Array&&n.bytes.byteLength<=e),fe=class extends Error{constructor(e){super(`Core transfer worker: ${e}.`),this.name="CoreTransferWorkerError",this.code=e}},Nt=()=>new DOMException("Core transfer was cancelled.","AbortError");function nl(n={}){let e={};for(let[t,r]of Object.entries(el)){let s=n[t]??r;if(!Number.isSafeInteger(s)||s<1||s>tl[t])throw new fe("invalid-limits");e[t]=s}return Object.freeze(e)}function sl(n,e){if(!n||!Array.isArray(n.pieces)||n.pieces.length<1||n.pieces.length>256)throw new fe("invalid-transfer");let t=n&&{size:n.size,sha256:n.sha256,pieces:n.pieces?.slice(),deadline:n.deadline,maxHolders:n.maxHolders,originReserveMs:n.originReserveMs,...n.peerOnly===!0?{peerOnly:!0}:{}};if(!t||!qe(t.size)||t.size<1||t.size>e.maxSegmentBytes||!ji(t.sha256)||!Array.isArray(t.pieces)||t.pieces.length<1||t.pieces.length>256||!t.pieces.every(ji)||!sr(t.deadline)||!qe(t.maxHolders)||t.maxHolders<1||t.maxHolders>32||!sr(t.originReserveMs)||n.peerOnly!==void 0&&typeof n.peerOnly!="boolean")throw new fe("invalid-transfer");return t}function il(n,e,t,r=!1){let[s,i,o]=e;if(!sr(s))throw new fe("invalid-operation");if(n==="start"){let a=i;if(!a||!Array.isArray(a.peers)||a.peers.length>32||!a.peers.every(l=>Array.isArray(l)&&l.length===3&&qe(l[0])&&nr(l[1])&&nr(l[2]))||(r?a.origin!=null:!Array.isArray(a.origin)||a.origin.length!==2||!a.origin.every(nr))||!nr(a.sharedFirstByteMs??null)||!nr(a.sharedRate??null)||!Array.isArray(a.probePeers??[])||(a.probePeers?.length??0)>32||!(a.probePeers??[]).every(qe))throw new fe("invalid-operation");return[s,{peers:a.peers.map(l=>[...l]),origin:r?null:[...a.origin],sharedFirstByteMs:a.sharedFirstByteMs??null,sharedRate:a.sharedRate??null,probePeers:[...a.probePeers??[]]}]}if(n==="tick")return[s];if(i!=="origin"&&!qe(i))throw new fe("invalid-operation");if(r&&i==="origin")throw new fe("invalid-operation");if(n==="failed")return[s,i];if(n==="progress"&&qe(o)&&o<=t)return[s,i,o];if(n==="delivered"&&o&&qe(o.start)&&qe(o.end)&&o.start0&&e.length<=2048)||typeof globalThis.Worker!="function"))throw new fe("worker-unavailable");let a=t??((k,W)=>new Worker(k,W)),l;try{l=a(e,{type:"module",name:"relayswarm-transfer"})}catch{throw new fe("worker-unavailable")}let c="loading",u=null,d=0,p=0,g=0,f=0,m=new Map,b=new Map,v=k=>{k.signal?.removeEventListener("abort",k.onAbort),b.get(k.id)===k&&(b.delete(k.id),f-=k.size)},w=(k,W=!0)=>{if(!(c==="stopped"||c==="failed")){c=W?"failed":"stopped",u=k.code??k.name,l.removeEventListener("message",K),l.removeEventListener("error",T),l.removeEventListener("messageerror",T),r?.removeEventListener("abort",O);for(let _ of m.values())clearTimeout(_.timer),_.settled||_.reject(k);m.clear(),g=0;for(let _ of b.values())_.closed=!0,v(_);try{l.terminate()?.catch?.(()=>{})}catch{}if(W)try{s?.(k)?.catch?.(()=>{})}catch{}}},T=k=>{k?.preventDefault?.(),w(new fe("worker-error"))},O=()=>w(Nt(),!1),K=({data:k})=>{if(!k||k.v!==1||!qe(k.id)||!m.has(k.id))return;let W=m.get(k.id);if(m.delete(k.id),g-=W.bytes,clearTimeout(W.timer),k.ok!==!0){let _=new fe(typeof k.error=="string"&&/^[a-z-]{1,40}$/.test(k.error)?k.error:"invalid-response");W.settled||W.reject(_),(k.fatal||k.ok!==!1)&&w(_)}else if(["init","new","free"].includes(W.op)?k.result!==!0:!rl(k.result,W.size)){let _=new fe("invalid-response");W.settled||W.reject(_),w(_)}else W.settled||W.resolve(k.result)},A=(k,W,_,F=0,P=[],N=!1)=>c==="stopped"||c==="failed"?Promise.reject(new fe("closed")):!N&&m.size>=o.maxPending||g+F>o.maxPendingBytes?Promise.reject(new fe("queue-limit")):new Promise((h,x)=>{let S=++d,M={resolve:h,reject:x,handle:W,bytes:F,op:k,size:b.get(W)?.size??o.maxSegmentBytes,settled:!1,timer:setTimeout(()=>w(new fe(k==="init"?"init-timeout":"operation-timeout")),k==="init"?o.initTimeoutMs:o.operationTimeoutMs)};m.set(S,M),g+=F;try{l.postMessage({v:1,id:S,op:k,handle:W,input:_},P)}catch{w(new fe("worker-message"))}});l.addEventListener("message",K),l.addEventListener("error",T),l.addEventListener("messageerror",T),r?.addEventListener("abort",O,{once:!0}),r?.aborted&&O();try{await A("init",null,{module:n,limits:o})}catch(k){throw w(k),k}if(c!=="loading")throw new fe("closed");return c="ready",Object.freeze({snapshot:()=>({state:c,reason:u,transfers:b.size,activeBytes:f,pending:m.size,pendingBytes:g}),stop:O,async transfer(k,{signal:W}={}){if(c!=="ready")throw new fe("closed");if(W?.aborted)throw Nt();let _=sl(k,o);if(b.size>=o.maxTransfers||f+_.size>o.maxActiveBytes)throw new fe("transfer-limit");let F={id:++p,size:_.size,closed:!1,signal:W,release:null};b.set(F.id,F),f+=_.size;let P=()=>{if(F.release)return F.release;F.closed=!0;for(let h of m.values())h.handle===F.id&&!h.settled&&(h.settled=!0,h.reject(Nt()));return F.release=A("free",F.id,null,0,[],!0).then(()=>!0,()=>!1).finally(()=>v(F))};F.onAbort=()=>{P()},W?.addEventListener("abort",F.onAbort,{once:!0});try{await A("new",F.id,_)}catch(h){throw F.closed||v(F),h}if(F.closed||W?.aborted)throw P(),Nt();let N=async(h,x)=>{if(F.closed)throw new fe("closed-transfer");try{let S=il(h,x,o.maxSegmentBytes,_.peerOnly===!0),M=0,H=[];if(h==="delivered"){if(M=S[3].byteLength,g+M>o.maxPendingBytes)throw new fe("queue-limit");S[3]=S[3].slice(),H=[S[3].buffer]}let D=await A(h,F.id,S,M,H);if(F.closed)throw Nt();return D}catch(S){throw P(),S}};return Object.freeze({start:(h,x)=>N("start",[h,x]),delivered:(h,x,S,M)=>N("delivered",[h,x,S,M]),failed:(h,x)=>N("failed",[h,x]),progress:(h,x,S)=>N("progress",[h,x,S]),tick:h=>N("tick",[h]),free:P,cancel:P,get closed(){return F.closed}})}})}function Ki(n,e,t){if(!Number.isSafeInteger(e)||!Number.isSafeInteger(t)||e<0||t<=e)return null;let r=Number.isSafeInteger(n?.rangeEnd)&&n.rangeEnd>0,s=r&&Number.isSafeInteger(n.rangeStart)?n.rangeStart:0;return r&&s+t>n.rangeEnd?null:{first:s+e,last:s+t-1}}function ut(n,e,t,r,s=null,i=null){if(typeof n=="function")try{let o=n({outcome:e,expectedBytes:Number.isSafeInteger(r-t)&&r>t?r-t:null,receivedBytes:Number.isSafeInteger(s)&&s>=0?s:null,httpStatus:Number.isInteger(i)&&i>=100&&i<=599?i:null});o&&typeof o.then=="function"&&Promise.resolve(o).catch(()=>{})}catch{}}function Vi(n,e,t,r,{signal:s,onIgnored:i,onResult:o}={}){let a=Ki(e,t,r);return!a||typeof n?.Loader!="function"||typeof e?.url!="string"||s?.aborted?(ut(o,s?.aborted?"abort":"invalid-request",t,r),Promise.resolve(null)):new Promise(l=>{let c=null,u=!1,d=(f,m,b=f?.byteLength??null,v=null)=>{if(!u){u=!0,s?.removeEventListener("abort",p);try{c?.destroy?.()}catch{}ut(o,m,t,r,b,v),l(f)}},p=()=>{try{c?.abort?.()}catch{}d(null,"abort")},g=f=>{let m=f instanceof ArrayBuffer?new Uint8Array(f):ArrayBuffer.isView(f)?new Uint8Array(f.buffer,f.byteOffset,f.byteLength):null;return m&&m.byteLength===r-t?m.slice():null};try{c=new n.Loader(n.config),s?.addEventListener("abort",p,{once:!0}),c.load({...e,responseType:"arraybuffer",rangeStart:a.first,rangeEnd:a.last+1},n.loaderConfig??{},{onSuccess:f=>{if(s?.aborted)return d(null,"abort");let m=g(f?.data);if(!m&&!u)try{i?.()}catch{}d(m,m?"payload":"wrong-size",f?.data?.byteLength??null,f?.code)},onError:f=>d(null,s?.aborted?"abort":"error",null,f?.code),onTimeout:()=>d(null,s?.aborted?"abort":"timeout"),onAbort:()=>d(null,"abort")})}catch{d(null,"exception")}})}function ol(n,{first:e,last:t}){if(n===null)return!0;let r=/^bytes (\d+)-(\d+)\/(\d+|\*)$/u.exec(n.trim());return!!r&&Number(r[1])===e&&Number(r[2])===t}async function $i(n,e,t,{signal:r,onIgnored:s,onResult:i,fetchImpl:o=globalThis.fetch}={}){let a=Ki(n,e,t);if(!a||typeof n?.url!="string"||typeof o!="function"||r?.aborted)return ut(i,r?.aborted?"abort":"invalid-request",e,t),null;let l;try{l=await o(n.url,{headers:{Range:`bytes=${a.first}-${a.last}`},signal:r,credentials:"same-origin"})}catch{return ut(i,r?.aborted?"abort":"error",e,t),null}let c=(u=null)=>{try{s?.()}catch{}return ut(i,"wrong-size",e,t,u,l.status),null};try{if(l.status!==206||!ol(l.headers.get("content-range"),a)){try{await l.body?.cancel()}catch{}return l.status===200||l.status===206?c():(ut(i,"error",e,t,null,l.status),null)}let u=new Uint8Array(await l.arrayBuffer());return u.byteLength!==t-e?c(u.byteLength):(ut(i,"payload",e,t,u.byteLength,l.status),u)}catch{return ut(i,r?.aborted?"abort":"error",e,t,null,l?.status),null}}var ke=Symbol("relayswarm-warm-ahead"),ze=24*1024*1024,Gi=3,Yn=4,Yi=8e3,qr=12e3,al=100,ft=n=>{let{start:e,duration:t}=n?.context?.frag??{};return Number.isFinite(e)&&e>=0&&Number.isFinite(t)&&t>0&&Number.isFinite(e+t)},Zn=(n,e)=>ft(n)&&n.context.frag.start<=e&&en===e||Math.abs(n-e)<=Math.min(1e-9,32*Number.EPSILON*Math.max(1,Math.abs(n),Math.abs(e))),dt=(n,e)=>n?.key===e?.key&&n?.scope===e?.scope&&ft(n)&&ft(e)&&Zi(n.context.frag.start,e.context.frag.start)&&Zi(n.context.frag.duration,e.context.frag.duration),ll=(n,e,t,r)=>{try{let{start:s,end:i}=n.loading;return n.aborted!==!0&&n.loaded===e&&[t,r,s,i].every(Number.isFinite)&&t>=0&&t<=s&&si!==void 0&&i!==0)||e.type!=="main"||!Number.isSafeInteger(e.level)||e.level<0||!Number.isSafeInteger(e.cc??0)||e.decryptdata?.method&&e.decryptdata.method!=="NONE")return null;let t=new URL(n.url??e.url),r=e.baseurl??e.base?.url;return!["http:","https:"].includes(t.protocol)||t.username||t.password||t.hash||typeof r!="string"?null:{context:{...n,url:t.href,frag:{sn:e.sn,cc:e.cc??0,type:e.type,level:e.level,url:t.href,baseurl:r,start:e.start,duration:e.duration,byteRangeStartOffset:e.byteRangeStartOffset,byteRangeEndOffset:e.byteRangeEndOffset},part:null,responseType:"arraybuffer"},key:JSON.stringify([t.href,r,e.type,e.level,e.sn,e.cc??0,0,0]),scope:JSON.stringify([r,e.type,e.level])}}catch{return null}}function Xi({Loader:n,next:e,authorise:t,verify:r,reserve:s=()=>!0,onVerified:i,onReuse:o,reuseBudget:a=()=>0,allowed:l=()=>!0,steady:c=!0,startupTarget:u=null,startupCommit:d=null,startupMaxBytes:p=ze,startupRecovery:g=()=>2e3}){if(!Number.isSafeInteger(p)||p32*1024*1024||p!==ze&&typeof u!="function")throw new RangeError("Invalid startup byte budget");let f=!1,m=0,b=null,v=null,w=[],T,O,K=null,A=0,k=new Map,W=new Set,_=new Map,F=new Set,P=new Set,N=new Map,h={enabled:typeof u=="function",state:u?"idle":"off",reason:null,owner:null,terminal:null,own:null,permit:null,response:null,verified:!1,reserved:0,controller:null,timer:null,poll:null,plan:[],cursor:null,frozenStart:null,hopAvailable:!0,checking:!1,targetTime:null,verifiedStart:null,verifiedEnd:null,requiredHeadroomMs:null,planningServiceMs:null,released:0,failures:0,cancellations:0,commitStarted:!1,commitCompleted:!1},x={started:0,verified:0,rejected:0,cancelled:0,coalesced:0,promotions:0,localReuseBytes:0,verifiedBytes:0,verifiedPeerBytes:0,consumedPeerBytes:0,cacheBytes:0,highWaterBytes:0},S=()=>[..._.values()].reduce((y,E)=>y+E.reserved,0),M=()=>h.reserved+S(),H=()=>h.state==="buffering"?p:ze,D=y=>x.cacheBytes+S()+y<=ze&&x.cacheBytes+M()+y<=H(),B=()=>new Set([...k.keys(),..._.keys(),...h.owner?[h.own.key]:[]]).size,U=()=>h.state==="buffering"?Yn:Gi,C=y=>_.get(y.key)===y&&!y.finished,z=y=>{let E=k.get(y);E&&(x.cacheBytes-=E.data.byteLength,k.delete(y))},ee=(y,E)=>{C(y)&&(y.finished=!0,_.delete(y.key),F.delete(y),b===y&&(b=null),y.reserved=0,y.finish(E),h.checking&&(h.recheck=!0),Ve(),queueMicrotask(ne))},te=y=>{C(y)&&(x.cancelled++,y.cancel(),ee(y,null))},$=()=>{(h.state==="idle"||h.state==="buffering")&&se("cancelled","cleared",!f),h.planningServiceMs=null,m++,w=[],K=null;for(let y of[..._.values()])te(y);for(let y of k.keys())z(y);for(let y of[...P])y(!0)},ne=()=>{if(f||b||!l()||!w.length||W.size+F.size>1||!c&&h.state!=="buffering"||h.state==="buffering"&&(!h.permit||h.checking)||h.state==="buffering"&&!Ut()||h.state==="buffering"&&B()>=U())return;let y=w.shift();if(k.has(y.key)||_.has(y.key)){queueMicrotask(ne);return}for(;B()>=Gi&&k.size&&h.state!=="buffering";)z(k.keys().next().value);if(B()>=U())return;let E=new AbortController,R=m,q=T,L=O,j,Y,Q,V={...y,reserved:0,finished:!1,waiters:new Set,genuineAt:null,promise:new Promise(X=>{Q=X}),noteDemand(){V.genuineAt??=performance.now(),y.context[ke]?.onGenuine?.()},genuine(){if(!C(V))return null;let X=[...V.waiters].find(de=>de.pendingTerminal&&ve(de.context)?.key===V.key);return X&&V.genuineAt!==null?{at:V.genuineAt,context:X.context}:null},promote(){clearTimeout(Y)},finish:X=>Q(X),cancel(){E.abort(),clearTimeout(Y);try{j?.abort(),j?.destroy()}catch{}}};b=V,_.set(V.key,V),Y=setTimeout(()=>te(V),Yi),(async()=>{try{let X=await t(y.context,E.signal);if(E.signal.aborted||f||R!==m||!C(V)||!l())return null;if(!X||!Number.isSafeInteger(X.size)||X.size<1||X.size>ze)return x.rejected++,null;for(;!D(X.size)&&k.size&&h.state!=="buffering";)z(k.keys().next().value);if(!D(X.size))return x.rejected++,null;if(V.reserved=X.size,!s(M()))return V.reserved=0,x.rejected++,null;x.highWaterBytes=Math.max(x.highWaterBytes,x.cacheBytes+M());let de=y.context[ke]={peerBytes:0,genuine:()=>V.genuine(),startupDependency:()=>{if(!Z()||!C(V)||!l()||!Dt(y))return null;try{return et()===null||!Z()?null:{at:h.entryAt,deadline:h.deadline,signal:h.controller.signal,context:y.context}}catch{return null}}};j=new n(q),x.started++;let J=performance.now(),re=await new Promise(ie=>j.load(y.context,L,{onSuccess:(me,he,Ce,Le)=>ie({response:me,stats:he,details:Le,serviceMs:ll(he,X.size,J,performance.now())}),onError:(...me)=>ie({failure:{name:"onError",args:me,stats:j.stats}}),onTimeout:(...me)=>ie({failure:{name:"onTimeout",args:me,stats:j.stats}}),onAbort:(...me)=>ie({failure:{name:"onAbort",args:me,stats:j.stats}}),onProgress:me=>{if(me?.loaded>X.size){E.abort();try{j.abort()}catch{}ie(null)}}}));if(re?.failure)return E.signal.aborted||f||R!==m||!C(V)?null:(x.rejected++,re);if(!re||E.signal.aborted||f||R!==m||!C(V)||!await r(X,re.response.data,y.context,E.signal))return x.rejected++,null;if(E.signal.aborted||f||R!==m||!C(V))return null;let le=re.response.data;if(le.byteLength!==X.size)return x.rejected++,null;if(V.reserved=0,i?.(X,le,y.context)===!1)return null;let pe={...re,context:y.context,scope:y.scope,data:le,permit:X,peerBytes:de.peerBytes,accept:de.accept};return k.set(y.key,pe),x.cacheBytes+=le.byteLength,x.verified++,x.verifiedBytes+=le.byteLength,x.verifiedPeerBytes+=de.peerBytes,Z()&&C(V)&&m===R&&y.scope===v&&Dt(y)&&(h.planningServiceMs=re.serviceMs),pe}catch{return E.signal.aborted||x.rejected++,null}finally{clearTimeout(Y);try{j?.destroy()}catch{}}})().then(X=>ee(V,X))},ue=(y,E,R,q)=>{K=null;let L=ve(y);if(!L||f)return null;v!==L.scope&&(v!==null&&$(),v=L.scope),T=E,O=R;let j=[];try{j=e(y).map(ve).filter(Boolean).filter(Q=>Q.scope===v).slice(0,2)}catch{}let Y=new Set([L.key,...j.map(Q=>Q.key)]);for(let Q of k.keys())Y.has(Q)||z(Q);for(let Q of[..._.values()])Y.has(Q.key)||te(Q);return w=j,ft(L)&&j.every(ft)&&(K={own:Oe(L),upcoming:j.map(Oe),owner:q}),L},Z=()=>{if(h.state!=="buffering"||f||h.revision!==m||h.owner?.pendingTerminal!==h.terminal||h.terminal.settled)return!1;let y=!1;try{y=dt(ve(h.terminal.context),h.identity)&&dt(ve(h.own.context),h.identity)&&h.terminal.context.url===h.contextUrl&&h.terminal.context.frag.url===h.fragUrl}catch{}return y?!0:(se("cancelled","context-changed"),!1)},oe=y=>({code:0,text:"RelaySwarm startup buffer unavailable",startupBufferReason:y}),ge=y=>e(y.context).map(ve).filter(Boolean).filter(E=>E.scope===v&&ft(E)).slice(0,2),Oe=y=>{let{key:E,scope:R,context:{url:q,frag:L}}=ve(y.context);return{key:E,scope:R,context:{url:q,frag:L,part:null,responseType:"arraybuffer"}}},Ke=(y,E)=>({...Oe(y),identity:Oe(y),parent:Oe(E)}),Ee=y=>{try{return dt(ve(y.context),y.identity)&&ge(y.parent).some(E=>dt(E,y.identity))}catch{return!1}},Dt=y=>{if(!Z()||K?.owner!==h.terminal.id)return!1;let E=h.plan.find(R=>dt(R.identity,y));return!!(E&&Ee(E))},se=(y,E,R=!0)=>{if(!["idle","buffering"].includes(h.state))return;let q=h.owner,L=h.terminal;h.state=y,h.reason=E,y==="failed"&&h.failures++,y==="cancelled"&&h.cancellations++,clearTimeout(h.timer),h.timer=null,clearTimeout(h.poll),h.poll=null,h.controller?.abort(),h.releasePins?.(),h.owner=null,h.terminal=null,h.response=null,h.reserved=0,w=[],h.plan=[],h.cursor=null,h.frozenStart=null,h.planningServiceMs=null;for(let j of[..._.values()])te(j);for(let j of k.keys())z(j);if(!(!q||!L||L.settled||q.pendingTerminal!==L)){L.settled=!0,q.pendingTerminal=null,q.token++,q.stats.aborted=!0;try{q.inner.abort()}catch{}!R||f||(y==="cancelled"?L.callbacks.onAbort?.(q.stats,L.context,null):L.callbacks.onError?.(oe(E),L.context,null,q.stats))}},et=()=>{let y;try{y=u()}catch{return se("failed","target-threw"),null}return y===null?(se("cancelled","target-unavailable"),null):!Number.isFinite(y)||y<0?(se("failed","invalid-target"),null):(h.targetTime=y,y)},St=()=>{let y;try{y=g(h.own.context)}catch{}return!Number.isFinite(y)||y<0?(se("failed","invalid-recovery"),null):(h.requiredHeadroomMs=y,y)},Et=(y,E)=>{if(!Z()||h.checking)return;if(h.frozenStart!==null&&y>=h.frozenStart&&(h.frozenStart=null),h.plan.some(L=>!Ee(L))||h.cursor&&!Ee(h.cursor))return se("cancelled","context-changed");for(;h.plan.length;){let L=h.plan[0],j=k.get(L.key),Y=_.get(L.key);if(L.context.frag.start+L.context.frag.duration>y||Y||j&&N.has(j.permit.key)||[...W].some(Q=>Q.pendingTerminal&&ve(Q.context)?.key===L.key))break;if(!j){if(!h.hopAvailable)return;h.hopAvailable=!1}if(h.cursor=L,h.plan.shift(),w=w.filter(Q=>Q.key!==L.key),!Z()||h.checking)return;z(L.key)}let R=2;if(h.verified&&h.response&&h.plan.length===2&&k.size===2&&!b&&!_.size&&!W.size&&!F.size&&h.plan.every(L=>k.has(L.key)&&!N.has(k.get(L.key).permit.key))){let L=tt(y);L.end!==null&&h.plan.every(j=>L.rows.includes(k.get(j.key)))&&(L.end-y)*1e3k.has(L.key)&&!N.has(k.get(L.key).permit.key))){let L=tt(y);L.end!==null&&(L.end-y)*1e3L.context.frag.start)?h.cursor:L??h.own,Y;try{Y=ge(j)[0]}catch{return se("cancelled","context-changed")}if(!Y)return;let Q=j.context.frag.start+j.context.frag.duration;if(Math.abs(Y.context.frag.start-Q)>.001||Y.key===h.own.key||h.plan.some(X=>X.key===Y.key))return se("cancelled","context-changed");let V=Ke(Y,j);if(Y.context.frag.start+Y.context.frag.duration<=y){if(!h.hopAvailable)return;h.hopAvailable=!1,h.cursor=V;return}h.plan.push(V),w.push(Y)}},Ut=()=>{if(!Z()||h.checking)return!1;let y=et();if(y===null||!Z())return!1;let E=St();if(E===null||!Z()||(Et(y,E),!Z()||h.checking||!w.length))return!1;if(h.frozenStart!==null&&yy)return!0;let R=w[0],q=h.plan.findIndex(L=>L.key===R.key);if(q<0)return se("cancelled","context-changed"),!1;if(h.verified){let L=tt(y);if(L.end!==null&&L.rows.filter(j=>j.context!==h.own.context).length>=2&&Math.abs(R.context.frag.start-L.end)<=.001)return!0}if(R.context.frag.start+R.context.frag.duration<=y+(E+(h.planningServiceMs??0))/1e3){if(!h.hopAvailable)return!1;h.hopAvailable=!1,h.cursor=h.plan[q],h.plan.splice(q,1),w.shift(),Et(y,E);let L=w[0]?.context.frag.start;return L>y&&(h.frozenStart=L),!1}return!0},Re=()=>{if(h.poll!==null||!Z())return;let y=h.deadline-performance.now();if(y<=0)return se("failed","deadline");h.poll=setTimeout(()=>{if(h.poll=null,!!Z()){if(!h.checking){h.hopAvailable=!0;let E=et();if(E===null||!Z())return;if(!l())return se("cancelled","not-allowed");let R=St();if(R===null||!Z()||(Et(E,R),!Z()))return;Ve(E),queueMicrotask(ne)}Re()}},Math.min(al,y))},tt=(y,E=null)=>{let R=h.verified&&h.response?[{...h.own,permit:h.permit}]:[],q=(E??[...R,...k.values()]).filter(Q=>Q.scope===v&&ft(Q)).sort((Q,V)=>Q.context.frag.start-V.context.frag.start),L=null,j=null,Y=[];for(let Q of q){let V=Q.context.frag.start,X=V+Q.context.frag.duration;L===null?V<=y&&yj&&(j=X,Y.push(Q))}return h.verifiedStart=L,h.verifiedEnd=j,{start:L,end:j,rows:Y}},Ie=(y=void 0)=>{if(!Z())return null;if(y===void 0&&(y=et()),y===null||!Z())return;if(!l())return se("cancelled","not-allowed");let E;try{E=g(h.own.context)}catch{}if(!Number.isFinite(E)||E<0)return se("failed","invalid-recovery");h.requiredHeadroomMs=E;let R=tt(y);if(!(R.end===null||(R.end-y)*1e3new Promise((E,R)=>{let q=!1,L=Y=>{q||(q=!0,y.removeEventListener("abort",j),Y?E():R(null))},j=()=>L(!1);if(y.addEventListener("abort",j,{once:!0}),y.aborted)return j();try{Promise.resolve(d(Object.freeze({signal:y}))).then(()=>L(!0),()=>L(!1))}catch{L(!1)}}),Ve=async(y=void 0)=>{if(!Z()||h.checking||!h.verified)return;let E=Ie(y);if(!E)return;h.checking=!0;let R=h.owner,q=h.terminal,L=m,j=new Map,Y=[],Q=!0,V=()=>{if(Q){Q=!1;for(let J of Y){let re=(N.get(J)??0)-1;re>0?N.set(J,re):N.delete(J)}h.releasePins===V&&(h.releasePins=null)}};h.releasePins=V;let X=()=>[...j.values()].some(({key:J,row:re,identity:le})=>k.get(J)!==re||!dt(ve(re.context),le)||re.data.byteLength!==re.permit.size)?(se("failed","coverage-evicted"),!1):[...j.values()].some(({key:J,row:re})=>!Dt({key:J,scope:re.scope,context:re.context}))?(se("cancelled","context-changed"),!1):!0,de=async({covered:J})=>{for(let[pe,ie]of k)J.rows.includes(ie)&&!j.has(ie)&&(j.set(ie,{key:pe,row:ie,identity:ve(ie.context)}),Y.push(ie.permit.key),N.set(ie.permit.key,(N.get(ie.permit.key)??0)+1));let re=[{context:h.own.context,permit:h.permit},...J.rows.filter(pe=>pe.context!==h.own.context)],le=await Promise.all(re.map(pe=>t(pe.context,h.controller.signal)));return()=>{if(!Z()||m!==L)return;if(le.some((he,Ce)=>!he||he.key!==re[Ce].permit.key||he.size!==re[Ce].permit.size||he.sha256!==re[Ce].permit.sha256))return se("failed","authority-changed");let pe=et();if(pe===null||!Z())return;if(!l())return se("cancelled","not-allowed");let ie;try{ie=g(h.own.context)}catch{}if(!Number.isFinite(ie)||ie<0)return se("failed","invalid-recovery");if(h.requiredHeadroomMs=ie,le.some((he,Ce)=>typeof he.current!="function"||he.current(re[Ce].context)!==!0))return se("failed","authority-changed");if(!Z())return;if(performance.now()>=h.deadline)return se("failed","deadline");if(!X())return;let me=tt(pe,J.rows);if(!(me.end===null||(me.end-pe)*1e3=h.deadline)return se("failed","deadline");if(h.commitCompleted=!0,!X())return;let ie=Ie();if(!ie||(J=await de(ie),!J()))return}let re=h.response,le=q.context[ke];if(o?.(q.context,re[0].data.byteLength,le?.peerBytes??0),!Z())return;if(!l())return se("cancelled","not-allowed");if((le?.commit??le?.accept)?.(q.context),!Z())return;le?.peerBytes>0&&(x.consumedPeerBytes+=le.peerBytes),h.state="ready",h.reason=null,h.released++,h.planningServiceMs=null,clearTimeout(h.timer),h.timer=null,clearTimeout(h.poll),h.poll=null,h.reserved=0;let pe=h.controller;if(h.owner=null,h.terminal=null,h.response=null,h.plan=[],h.cursor=null,h.frozenStart=null,!c){w=[];for(let ie of[..._.values()])te(ie)}try{R.deliver(q,"onSuccess",re)}finally{try{pe.abort()}finally{le?.notify?.()}}}catch{Z()&&se("failed","authority-refused")}finally{V(),h.checking=!1,h.state==="buffering"&&(queueMicrotask(ne),h.recheck&&(h.recheck=!1,queueMicrotask(Ve)))}},Yr=(y,E,R,q)=>{if(!h.enabled)return!0;if(h.state==="failed"||h.state==="cancelled")return h.state==="cancelled"&&(y.stats.aborted=!0),y.deliver(E,h.state==="cancelled"?"onAbort":"onError",h.state==="cancelled"?[y.stats,E.context,null]:[oe(h.reason),E.context,null,y.stats]),!1;if(!R)return h.state==="idle"&&E.context.frag?.type==="main"&&E.context.frag.sn!=="initSegment"?(h.state="failed",h.reason="unsupported-context",h.failures++,y.deliver(E,"onError",[oe(h.reason),E.context,null,y.stats]),!1):!0;if(h.state==="buffering")return se("cancelled","superseded"),y.deliver(E,"onAbort",[y.stats,E.context,null]),!1;if(h.state!=="idle")return!0;let L=performance.now(),j=q?.loadPolicy?.maxLoadTimeMs??q?.timeout;if(Object.assign(h,{state:"buffering",owner:y,terminal:E,own:R,revision:m,reserved:p,entryAt:L,identity:{key:R.key,scope:R.scope,context:{frag:{start:R.context.frag.start,duration:R.context.frag.duration}}},contextUrl:E.context.url,fragUrl:E.context.frag.url,controller:new AbortController,deadline:L+Math.min(qr,Number.isFinite(j)&&j>0?j:qr)}),h.plan=(K?.upcoming??[]).map(Y=>Ke(Y,R)),K?.owner===E.id&&(K.rolling=h.plan),h.cursor=null,E.context[ke]={peerBytes:0,genuine:()=>Z()?{at:L,context:E.context}:null},!ft(R)||!l())return se("failed","not-allowed"),!1;if(y.config.progressive===!0)return se("failed","progressive-unsupported"),!1;if(et()===null||!Z())return!1;try{if(!s(M()))return se("failed","reservation-refused"),!1}catch{return se("failed","reservation-refused"),!1}return Z()?l()?(h.timer=setTimeout(()=>se("failed","deadline"),Math.max(0,h.deadline-performance.now())),Re(),Promise.resolve().then(()=>Z()?t(R.context,h.controller.signal):null).then(Y=>{if(Z()){if(!Y||!Number.isSafeInteger(Y.size)||Y.size<1||Y.size>ze)return se("failed","first-authority-refused");if(h.permit=Y,h.reserved=Y.size,!s(M()))return se("failed","reservation-refused");x.highWaterBytes=Math.max(x.highWaterBytes,x.cacheBytes+M()),ir(),queueMicrotask(ne)}}).catch(()=>{Z()&&se("failed","first-authority-refused")}),!0):(se("cancelled","not-allowed"),!1):!1},ir=async()=>{if(!(!Z()||!h.response||!h.permit||h.verifying||h.verified)){h.verifying=!0;try{let y=h.response[0].data,E=h.permit;if(!(y instanceof ArrayBuffer)||y.byteLength!==E.size||!await r(E,y,h.own.context,h.controller.signal))return Z()&&se("failed","first-integrity");if(!Z())return;h.verified=!0,x.verified++,x.verifiedBytes+=y.byteLength,x.verifiedPeerBytes+=h.terminal.context[ke]?.peerBytes??0,Ve()}catch{Z()&&se("failed","first-integrity")}finally{h.verifying=!1}}};return{Loader:class{static relayswarmShadow=!0;constructor(E){this.config=E,this.inner=new n(E),this.stats=this.inner.stats,this.context=null,this.token=0}load(E,R,q){this.abort(),this.context=E;let L={id:++A,context:E,callbacks:{...q},settled:!1};this.pendingTerminal=L,q={...q};for(let de of["onSuccess","onError","onTimeout","onAbort"])q[de]=(...J)=>this.complete(L,de,J);let j=++this.token,Y=ue(E,this.config,R,L.id),Q=Y&&k.get(Y.key);if(!Yr(this,L,Y,R))return;let V=!Q&&Y&&_.get(Y.key),X=Q??V?.promise;if(X){V&&(x.coalesced++,V.waiters.add(this),this.warmPending=V,V.noteDemand(),b===V&&F.size===0&&(b=null,F.add(V),V.promote(),x.promotions++)),this.reuseAbort=new AbortController;let de=m,J=null,re,le=null,pe=()=>j===this.token,ie=()=>{if(clearTimeout(re),P.delete(me),le!==null){let he=N.get(le)-1;he>0?N.set(le,he):N.delete(le),le=null}},me=(he=!1)=>{if(he&&(ie(),this.reuseAbort.abort()),!pe()||J||this.originStarted)return;this.originStarted=!0,clearTimeout(re);let Ce={...q,onProgress:(...Le)=>{!pe()||J==="cache"||(Le[2]?.byteLength>0&&(J="origin",this.reuseAbort.abort(),ie()),q.onProgress?.(...Le))}};for(let Le of["onSuccess","onError","onTimeout","onAbort"])Ce[Le]=(...zt)=>{!pe()||J==="cache"||(J="origin",this.reuseAbort.abort(),ie(),q[Le]?.(...zt))};this.start(E,R,Ce,j)};this.cancelReuse=()=>{ie(),this.reuseAbort.abort()},P.add(me),Promise.resolve(X).then(async he=>{if(!pe())return;if(this.releasePending(),f||!he||de!==m)return me(!0);if(he.failure){let{name:ts,args:Xr,stats:rs}=he.failure;J="origin",ie(),this.reuseAbort.abort(),rs&&Object.assign(this.stats,rs),ts==="onError"?q.onError(Xr[0],E,Xr[2],this.stats):q[ts](this.stats,E,Xr[2]);return}le=he.permit.key,N.set(le,(N.get(le)??0)+1);let Ce=Math.max(0,Math.min(25,a(E)||0));Ce>0?re=setTimeout(me,Ce):me();let Le;try{Le=await t(E,this.reuseAbort.signal)}catch{}if(!pe()||J==="origin")return;if(f||de!==m)return me(!0);if(!Le||Le.key!==he.permit.key||Le.size!==he.permit.size||Le.sha256!==he.permit.sha256)return z(Y.key),me();J="cache",ie(),this.originStarted&&this.inner.abort(),Object.assign(this.stats,he.stats);let zt=he.data.slice(0);x.localReuseBytes+=zt.byteLength,he.accepted||(he.accepted=!0,he.accept?.(E),x.consumedPeerBytes+=he.peerBytes),o?.(E,zt.byteLength,he.peerBytes),q.onSuccess({...he.response,data:zt},this.stats,E,he.details),queueMicrotask(ne)})}else this.start(E,R,q,j);queueMicrotask(ne)}start(E,R,q,L){W.add(this),W.size+F.size>1&&b&&te(b);let j=this.pendingTerminal,Y=()=>{W.delete(this),queueMicrotask(ne)},Q={...q};Q.onProgress=(...V)=>{if(!(f||L!==this.token||!j||j.settled||this.pendingTerminal!==j)){if(h.owner===this&&(V[0]?.loaded>(h.permit?.size??ze)||V[2]?.byteLength>(h.permit?.size??ze)))return se("failed","first-oversize");if(h.owner===this&&V[2]!==null&&V[2]!==void 0){Z();return}q.onProgress?.(...V)}};for(let V of["onSuccess","onError","onTimeout","onAbort"])Q[V]=(...X)=>{Y(),L===this.token&&q[V]?.(...X)};this.inner.load(E,R,Q)}releasePending(){let E=this.warmPending;this.warmPending=null,E&&(E.waiters.delete(this),E.waiters.size||E.context[ke]?.onGenuine?.(),F.has(E)&&!E.waiters.size&&te(E))}complete(E,R,q){if(!(!E||E.settled||this.pendingTerminal!==E)){if(h.owner===this&&h.terminal===E&&h.state==="buffering"){if(R==="onSuccess"){let L=q[0]?.data;if(!(L instanceof ArrayBuffer)||L.byteLength>(h.permit?.size??ze))return se("failed","first-oversize");h.response=q,ir();return}h.state=R==="onAbort"?"cancelled":"failed",h.reason=R==="onAbort"?"origin-abort":"origin-error",R==="onAbort"?h.cancellations++:h.failures++,clearTimeout(h.timer),clearTimeout(h.poll),h.poll=null,h.controller?.abort(),h.releasePins?.(),h.owner=null,h.terminal=null,h.response=null,h.reserved=0,w=[],h.plan=[],h.cursor=null,h.frozenStart=null,h.planningServiceMs=null;for(let L of[..._.values()])te(L);for(let L of k.keys())z(L)}this.deliver(E,R,q)}}deliver(E,R,q){!E||E.settled||this.pendingTerminal!==E||(R!=="onSuccess"&&K?.owner===E.id&&(K=null),E.settled=!0,this.pendingTerminal=null,E.callbacks[R]?.(...q))}cancel(E){let R=this.pendingTerminal;h.owner===this&&h.terminal===R&&se("cancelled","caller-abort",!E&&!f),R&&K?.owner===R.id&&(K=null),this.token++,this.originStarted=!1,this.cancelReuse?.(),this.releasePending(),W.delete(this),R&&(this.stats.aborted=!0),E&&R&&(R.settled=!0,this.pendingTerminal=null);try{E?this.inner.destroy():this.inner.abort()}finally{E||this.complete(R,"onAbort",[this.stats,R?.context,null])}}abort(){this.cancel(!1)}destroy(){this.cancel(!0)}getCacheAge(){return this.inner.getCacheAge?.()??null}getResponseHeader(E){return this.inner.getResponseHeader?.(E)??null}},clear:$,startupSnapshot:()=>({enabled:h.enabled,state:h.state,reason:h.reason,heldObjects:h.state==="buffering"?B():0,heldBytes:h.state==="buffering"?x.cacheBytes+M():0,targetTime:h.targetTime,verifiedStart:h.verifiedStart,verifiedEnd:h.verifiedEnd,requiredHeadroomMs:h.requiredHeadroomMs,planningServiceMs:h.planningServiceMs,released:h.released,failures:h.failures,cancellations:h.cancellations,commitStarted:h.commitStarted,commitCompleted:h.commitCompleted,limits:{objects:Yn,bytes:p,futureBytes:ze,deadlineMs:qr}}),contains(y){if(f||!l()||!Number.isFinite(y))return!1;for(let R of[..._.values(),...k.values()])if(R.scope===v&&Zn(R,y))return!0;let E=K;if(!E||E.own.scope!==v||!Zn(E.own,y))return!1;try{let R=E.rolling??e(E.own.context).map(ve).filter(Boolean).filter(L=>L.scope===v).slice(0,2),q=new Map([E.own,...R].map(L=>[L.key,L]));return(E.rolling?R.some(L=>!Ee(L)):R.length!==E.upcoming.length||R.some((L,j)=>!dt(L,E.upcoming[j])))||[..._,...k].some(([L,j])=>!dt({...j,key:L},q.get(L)))?(K=null,!1):!0}catch{K=null}return!1},pinned:y=>N.has(y),release(y){for(let[E,R]of k)R.permit.key===y&&z(E)},stop(){f=!0,$()},snapshot:()=>({...x,reservationBytes:M(),active:+!!b,promoted:F.size,trackedObjects:B(),queued:w.length,cacheObjects:k.size,limits:{objects:U(),bytes:H(),speculativeWholeRequests:1,deadlineMs:h.state==="buffering"?qr:Yi,revalidationMs:25}})}}function Ji({now:n,take:e,give:t,delay:r,validate:s,refuse:i,maxWaiters:o}){let a=new Map,l=new Set,c={waited:0,waitTotalMs:0,waitMaxMs:0,granted:0,expired:0,cancelled:0,refused:0},u=!1,d=null,p=v=>{if(!v.waiting)return;let w=Math.max(0,n()-v.queuedAt);c.waited++,c.waitTotalMs+=w,c.waitMaxMs=Math.max(c.waitMaxMs,w)},g=(v,w)=>{a.get(v.link)===v&&(a.delete(v.link),p(v),c[w]++,i(w),v.resolve(null))},f=(v,w=!1)=>{l.delete(v)&&(v.active=!1,w||t(v.charge),queueMicrotask(m))},m=()=>{if(clearTimeout(d),d=null,!u)for(;a.size;){let v=a.values().next().value;if(n()>=v.deadline){g(v,"expired");continue}if(!s(v)){g(v,"cancelled");continue}if(!e(v.charge)){v.waiting=!0;let w=v.deadline-n();d=setTimeout(m,Math.max(1,Math.ceil(Math.min(w,r(v.charge)))));return}a.delete(v.link),p(v),v.active=!0,v.controller=new AbortController,l.add(v),c.granted++,v.resolve(v)}},b=v=>{for(let w of[...a.values()])(!v||w.link===v)&&g(w,"cancelled");for(let w of[...l])(!v||w.link===v)&&(c.cancelled++,w.controller.abort(),f(w));m()};return{acquire(v,w){return u||a.has(v)||[...l].some(T=>T.link===v)||a.size>=o||!w.range&&(a.size||r(w.charge)>0)?(c.refused++,i("refused"),Promise.resolve(null)):new Promise(T=>{let O=n();a.set(v,{link:v,key:w.key,size:w.size,charge:w.charge,range:w.range?{start:w.range.start,end:w.range.end}:null,queuedAt:O,deadline:O+250,resolve:T,waiting:a.size>0,active:!1}),m()})},finish:f,cancel:b,recheck:m,stop(){u=!0,b(),clearTimeout(d),d=null},snapshot:()=>({enabled:!0,...c,queued:a.size,reservedBytes:[...l].reduce((v,w)=>v+w.charge,0),limits:{waitMs:250,waiters:o,perLink:1}})}}var hl=2,jr="webrtc",Xn=16,Jn=3e4,ul=1e4,Wr=300,Kr=32*1024,Qi=Object.freeze({mode:"shadow",originFallbackMs:1500,maxPeerWaitMs:5e3,originReserveMs:2e3,sustainablePeerWait:!1,warmAhead:!1,startupBufferTarget:null,startupBufferMaxBytes:24*1024*1024,startupBufferCommit:null,lateWindowMs:6e3,maxPeers:6,maxUploadPeers:4,maxUploadBytesPerSecond:125e4,uploadPacing:!1,maxUploadBytesPerSession:void 0,maxDialsInFlight:2,dialTimeoutMs:12e3,presenceIntervalMs:2e4,metricsIntervalMs:1e4,maxHeldSegments:12,maxHeldBytes:64*1024*1024,maxSegmentBytes:16*1024*1024,shadowSampleRate:.25,maxConcurrentRaces:24,admissionTimeoutMs:3e3,swarmParts:!1,serveOnCellular:!1,serve:!1,ticket:void 0,admit:void 0,minLinkLifeMs:15e3,idleEvictMs:2e4,evictionCooldownMs:1e4,retryFloorMs:4e3,retryCeilingMs:45e3,maxRetriesPerPeer:3,maxReferrals:2,reannounceDebounceMs:4e3,minReannounceGapMs:12e3,iceServers:[{urls:"stun:stun.l.google.com:19302"}],iceTransportPolicy:"all",coreWasm:void 0,transferWorkerUrl:void 0,multiHolder:!1,zeroBudgetPeerRace:!1,lateHaveRace:!1,latePeerRace:!1,maxHoldersPerObject:3,traceRequests:0,abrIgnorePeers:!1,peerSupplyHint:!1,onPlayerHint:null,onPeerDelivery:null}),dl=32768,fl=500,pl=2e3,I=()=>performance.now(),Vr=n=>{let e=n?.loading?.first;return Date.now()-(Number.isFinite(e)&&e>0&&e<=I()?I()-e:0)},ao=n=>Array.from(new Uint8Array(n),e=>e.toString(16).padStart(2,"0")).join(""),eo=new TextEncoder;async function Pt(n){return ao(await globalThis.crypto.subtle.digest("SHA-256",n))}function to(n){return new URL(n,globalThis.location?.href).pathname}function gl(n){try{return new URL(n,globalThis.location?.href).origin}catch{return String(n)}}function Be(n,e){if(!n.length)return null;let t=[...n].sort((r,s)=>r-s);return Math.round(t[Math.min(t.length-1,Math.floor(e*t.length))])}function ml(n,e){if(!n.length)return null;let t=[...n].sort((r,s)=>r-s);return t[Math.min(t.length-1,Math.floor(e*t.length))]}function Qn(n){return{p50:Be(n,.5),p90:Be(n,.9)}}function je(n,e){n.push(e),n.length>fl&&n.shift()}function Ht(){let n=globalThis.navigator?.connection;return!!(n&&(n.type==="cellular"||n.saveData))}var $r=Object.freeze({created:["outgoing","incoming"],gathering:["new","gathering","complete","unknown"],ice:["new","checking","connected","completed","failed","disconnected","closed","unknown"],connection:["new","connecting","connected","disconnected","failed","closed","unknown"],"local-offer":["complete","capped","aborted","unknown"],"local-answer":["complete","capped","aborted","unknown"],"offer-received":["authenticated"],"answer-received":["authenticated"],"offer-admitted":["accepted"],"answer-admitted":["accepted"],"remote-installed":["offer","answer"],"signal-send":["offer","answer"],"signal-failed":["offer","answer"],"channel-open":["accepted","stale"],negotiation:["glare-yield"],"dial-end":["timeout","failed","rejected","superseded","admission","host-stop"],"link-close":["host","host-stop","admission","rotation","integrity","request-timeout","request-abort","native-failed","native-closed","native-disconnected","channel-close","channel-error","protocol","send-error","serve-error","upload-queue","upload-drain-timeout"]}),We=n=>Math.min(Number.MAX_SAFE_INTEGER,n+1),ro=Object.freeze(["no-budget","aborted-before-eligibility","no-have-no-wait","no-have-wait","wait-no-longer-eligible","wait-aborted","wait-expired","have-at-entry","have-after-wait","projected-late"]),no=Object.freeze(["payload","none","timeout","abort","abandoned","closed","busy","send-error"]),yl=15e3,bl=250,wl=50,so=Object.freeze(["presence","dialStart","offerBeforeSend","offerIncoming","answerIncoming","glareBeforeRollback","glareAfterRollback","answerBeforeSend","upload","refresh","other"]),vl=Object.freeze(["admission","not-held","not-serving","banned","session-allowance","peer-limit","rate-limit","reservation-refused","reservation-inactive"]);function io(n,e=1200,t,r){return new Promise(s=>{let i=c=>{try{r?.(c)}catch{}s(c)};if(n.iceGatheringState==="complete"||t?.aborted)return i(t?.aborted?"aborted":"complete");let o=()=>{clearTimeout(l),n.removeEventListener("icegatheringstatechange",a),t?.removeEventListener("abort",o);let c="unknown";try{c=t?.aborted?"aborted":n.iceGatheringState==="complete"?"complete":"capped"}catch{}i(c)},a=()=>{n.iceGatheringState==="complete"&&o()},l=setTimeout(o,e);n.addEventListener("icegatheringstatechange",a),t?.addEventListener("abort",o,{once:!0})})}async function xl(n){try{let e=await n.getStats(),t=null;return e.forEach(r=>{r.type==="transport"&&r.selectedCandidatePairId&&(t=e.get(r.selectedCandidatePairId)||t)}),t||e.forEach(r=>{r.type==="candidate-pair"&&r.state==="succeeded"&&(r.selected||r.nominated)&&(t=r)}),t?`${e.get(t.localCandidateId)?.candidateType||"?"}/${e.get(t.remoteCandidateId)?.candidateType||"?"}`:"unknown"}catch{return"unknown"}}function Sl(){return ao(globalThis.crypto.getRandomValues(new Uint8Array(12)))}function oo(n,{minLinkLifeMs:e,idleEvictMs:t,banned:r=new Set,tier:s}={},i=Date.now()){let o=null,a=0;for(let l of n){if(l.transferring||r.has(l.pubkey)||i-l.openedAttypeof i=="string"&&/^[0-9a-f]{64}$/u.test(i)).slice(0,e.maxReferrals):[];return{retryAfterMs:r,referrals:s}}function kl(n={}){let e=new es(n);return{attach:t=>e.attach(t),updateTicket:t=>e.updateTicket(t),stop:()=>e.stop(),metrics:()=>e.metrics(),peerConnections:()=>e.peerConnections(),peerConnectionDetails:()=>e.peerConnectionDetails(),trace:()=>e.trace()}}var es=class{constructor(e){this.options={...Qi,...e},this.options.iceTransportPolicy===void 0&&(this.options.iceTransportPolicy=Qi.iceTransportPolicy),this.startedAt=Date.now(),this.transportStartedAt=I(),this.transportSequence=0,this.transportRecords=[],this.transportDropped=0,this.transportCounters=Object.fromEntries(Object.entries($r).map(([t,r])=>[t,Object.fromEntries(r.map(s=>[s,0]))])),this.transportConnections=new WeakMap,this.peerEligibilityRecords=[],this.peerEligibilityDropped=0,this.peerEligibilityCounters=Object.fromEntries(ro.map(t=>[t,0])),this.holderLabels=new Map,this.traceRows=[],this.traceDropped=0,this.traceLoads=new WeakMap,this.traceLoadNext=1,this.traceBase=Math.floor(I()),this.holderLabelNext=1,this.peerRequestRecords=[],this.peerRequestDropped=0,this.peerRequestCounters=Object.fromEntries(no.map(t=>[t,0])),this.uploadRefusalCounters=Object.fromEntries(vl.map(t=>[t,0])),this.admissionCallCounters=Object.fromEntries(so.map(t=>[t,0])),this.disabledReason=this.#r(),this.stopped=!1,this.lifecycle=new AbortController,this.admissionChecks=new Map,this.dialChecks=new Set,this.hls=null,this.originalFragmentLoader=void 0,this.pool=null,this.session=null,this.timers=new Set,this.links=new Map,this.peerLeases=new Map,this.peerLeaseWaiters=new Set,this.peerAdmission={claims:0,waited:0,granted:0,expired:0,cancelled:0},this.latePeerOwners=new Map,this.latePeerGeneration=0,this.latePeerNextId=1,this.latePeerRows=[],this.latePeerDropped=0,this.latePeerCounts={entered:0,armed:0,won:0,expired:0,retired:0,refused:0},this.peerSelection=new wt,this.linkTimings=new WeakMap,this.core=null,this.coreVerifier=null,this.coreState="off",this.transferWorker=null,this.transferWorkerState=this.options.transferWorkerUrl===void 0?"off":"waiting-core",this.transferWorkerReason=null,this.coreWait=null,this.coreRelease=null,this.remoteFraming=new Map,this.transferIds=new WeakMap,this.nextTransferId=1,this.multiHolder={transfers:0,delivered:0,late:0,failed:0,bans:0,abandoned:0,peerBytes:0,originBytes:0,unusedBytes:0,originRanges:0,originRangesIgnored:0},this.originRangeOutcomes=Object.fromEntries(["payload","invalid-request","wrong-size","error","timeout","abort","exception"].map(t=>[t,0])),this.originsWithoutRanges=new Set,this.multiHolderTimings=[],this.coreFallbacks=0,this.coreDecided={wasm:0,js:0},this.coreLinks={wasm:0,js:0},this.dials=new Map,this.receivedOffers=new Set,this.cooldowns=new Map,this.retries=new Map,this.openPeers=new Map,this.discovery=new _t,this.lastEvictionAt=0,this.lastAnnouncedAt=0,this.reannounceTimer=null,this.banned=new Set,this.admitted=new Map,this.held=new Map,this.heldBytes=0,this.races=new Set,this.cachedRaces=new Set,this.haveWaiters=new Set,this.rendition=null,this.renditions=new Map,this.originFetches=new Map,this.uploadQuotaBytes=0,this.uploadTokens=this.options.maxUploadBytesPerSecond,this.uploadRefilledAt=I(),this.uploadPacer=this.options.uploadPacing?Ji({now:I,maxWaiters:Math.min(this.options.maxUploadPeers,this.options.maxPeers),take:t=>(this.#Ee(),this.uploadTokens{this.uploadTokens=Math.min(this.options.maxUploadBytesPerSecond*2,this.uploadTokens+t)},delay:t=>(this.#Ee(),Math.max(0,(t-this.uploadTokens)*1e3/this.options.maxUploadBytesPerSecond)),validate:t=>this.#ke(t),refuse:t=>this.#y(t==="cancelled"?"not-serving":"rate-limit")}):null,this.playerHints=[],this.hintSizes=new Map,this.hintOriginRates=[],this.hintGeneration=0,this.peerFragments=new WeakSet,this.originalTrigger=null,this.counters={originLoaded:0,sampledOriginBytes:0,peerInTimeBytes:0,peerFirstLoaded:0,peerFirstBytes:0,zeroBudgetPeerRaces:0,zeroBudgetPeerRaceWins:0,abrPeerSamplesWithheld:0,originFallbacks:0,coordinatedWaits:0,coordinatedPeerLoads:0,peerSkippedLate:0,peerProjectedLate:0,peerWaitExtended:0,peerAbandoned:0,peerNoFit:0,peerUntestedTrial:0,peerUntestedTrialLoaded:0,commitmentRequests:0,commitmentRejected:0,commitmentUnavailable:0,raced:0,noPeers:0,sampledOut:0,skipped:0,peerInTime:0,peerLate:0,peerMiss:0,peerCorrupt:0,peerUnverified:0,aborted:0,bytesFromOrigin:0,bytesFromPeers:0,bytesUploaded:0,uploadsServed:0,uploadsRefused:0,uploadsCancelled:0,uploadCancelledBytes:0,dialsStarted:0,dialsAccepted:0,dialsFailed:0,dialsTimedOut:0,dialsRejected:0,offersAccepted:0,offersRefused:0,admitRefused:0,evicted:0,evictedUnhelpful:0,evictedServing:0,evictedConsumer:0,evictionsUnavailable:0,retriesScheduled:0,referralsSent:0,referralsFollowed:0,linksOpened:0,linksClosed:0,presenceSent:0,signalsSent:0,publishErrors:0,errors:0},this.firstLinkAtMs=null,this.firstPeerSegmentAtMs=null,this.pairTypes={},this.signallingSamples=[],this.originClockSamples=[],this.peerLatencySamples=[],this.originLatencySamples=[],this.renditionOriginSamples=new Map,this.renditionSizes=new Map,this.errorsByStage={}}#r(){let{swarmId:e,relays:t,mode:r}=this.options;if(typeof e!="string"||e.length<8||e.length>128)return"invalid-swarm-id";if(!Array.isArray(t)||t.length<1||t.length>8)return"invalid-relays";try{for(let o of t){let a=new URL(o);if(a.protocol!=="wss:"&&!(a.protocol==="ws:"&&["localhost","127.0.0.1","[::1]"].includes(a.hostname)))return"invalid-relays"}}catch{return"invalid-relays"}if(!["all","relay"].includes(this.options.iceTransportPolicy))return"invalid-ice-transport-policy";if(r==="off")return"mode-off";if(r!=="shadow"&&r!=="peer-first")return"invalid-mode";if(r==="peer-first"&&!Hr(this.options.streamEvent))return"invalid-stream-authorisation";if(r==="peer-first"&&typeof this.options.getCommitment!="function")return"missing-commitment-provider";let s=this.options.coreWasm;if(s!==void 0&&!(typeof s=="string"||s instanceof URL||s instanceof ArrayBuffer||ArrayBuffer.isView(s)||typeof WebAssembly=="object"&&s instanceof WebAssembly.Module))return"invalid-core-wasm";if(typeof this.options.multiHolder!="boolean"||!Number.isSafeInteger(this.options.maxHoldersPerObject)||this.options.maxHoldersPerObject<1||this.options.maxHoldersPerObject>8)return"invalid-multi-holder";let i=this.options.transferWorkerUrl;if(i!==void 0&&(r!=="peer-first"||!this.options.multiHolder||s===void 0||!(i instanceof URL||typeof i=="string"&&i.length>0&&i.length<=2048))||this.options.WorkerImpl!==void 0&&typeof this.options.WorkerImpl!="function")return"invalid-transfer-worker";if(!Number.isSafeInteger(this.options.traceRequests)||this.options.traceRequests<0||this.options.traceRequests>dl)return"invalid-trace";if(typeof this.options.peerSupplyHint!="boolean"||this.options.onPlayerHint!==null&&typeof this.options.onPlayerHint!="function")return"invalid-player-hint-option";if(typeof this.options.abrIgnorePeers!="boolean")return"invalid-abr-option";if(typeof this.options.zeroBudgetPeerRace!="boolean")return"invalid-cached-race-option";if(typeof this.options.lateHaveRace!="boolean")return"invalid-late-have-race-option";if(typeof this.options.latePeerRace!="boolean"||this.options.latePeerRace&&(r!=="peer-first"||!this.options.zeroBudgetPeerRace))return"invalid-late-peer-race-option";if(typeof this.options.sustainablePeerWait!="boolean")return"invalid-sustainable-wait-option";if(typeof this.options.warmAhead!="boolean"||this.options.warmAhead&&(r!=="peer-first"||this.options.serve!==!0))return"invalid-warm-ahead-option";if(this.options.startupBufferTarget!==null&&(typeof this.options.startupBufferTarget!="function"||r!=="peer-first"||this.options.serve!==!0))return"invalid-startup-buffer-target";if(!Number.isSafeInteger(this.options.startupBufferMaxBytes)||this.options.startupBufferMaxBytes<24*1024*1024||this.options.startupBufferMaxBytes>32*1024*1024||this.options.startupBufferMaxBytes!==24*1024*1024&&typeof this.options.startupBufferTarget!="function")return"invalid-startup-buffer-max-bytes";if(this.options.startupBufferCommit!==null&&(typeof this.options.startupBufferCommit!="function"||typeof this.options.startupBufferTarget!="function"))return"invalid-startup-buffer-commit";if(this.options.admit!==void 0&&typeof this.options.admit!="function")return"invalid-admit";if(this.options.reserveUploadBytes!==void 0&&typeof this.options.reserveUploadBytes!="function")return"invalid-upload-reservation";if(typeof this.options.serve!="boolean"||typeof this.options.serveOnCellular!="boolean")return"invalid-serve-option";if(typeof this.options.uploadPacing!="boolean")return"invalid-upload-pacing";if(this.options.ticket!==void 0&&!ye(this.options.ticket))return"invalid-ticket";if(this.options.maxUploadBytesPerSession!==void 0&&(!Number.isSafeInteger(this.options.maxUploadBytesPerSession)||this.options.maxUploadBytesPerSession<0))return"invalid-upload-session-limit";for(let o of["originFallbackMs","maxPeerWaitMs","originReserveMs","lateWindowMs","maxPeers","maxUploadPeers","maxUploadBytesPerSecond","maxDialsInFlight","dialTimeoutMs","presenceIntervalMs","metricsIntervalMs","maxHeldSegments","maxHeldBytes","maxSegmentBytes","maxConcurrentRaces","admissionTimeoutMs"])if(!Number.isSafeInteger(this.options[o])||this.options[o]<1)return"invalid-limits";return!Number.isFinite(this.options.shadowSampleRate)||this.options.shadowSampleRate<0||this.options.shadowSampleRate>1?"invalid-sample-rate":globalThis.crypto?.subtle?typeof(this.options.RTCPeerConnectionImpl||globalThis.RTCPeerConnection)!="function"?"no-webrtc":typeof(this.options.WebSocketImpl||globalThis.WebSocket)!="function"?"no-websocket":"":"no-webcrypto"}attach(e){if(!(this.stopped||this.hls||this.disabledReason||!e?.config))try{this.hls=e,this.originalFragmentLoader=e.config.fLoader;let t=e.config.fLoader||e.config.loader;if(e.config.fLoader=this.options.mode==="peer-first"?this.#b(t):this.#Qe(t),this.options.warmAhead||this.options.startupBufferTarget){this.warmAhead=Xi({Loader:e.config.fLoader,steady:this.options.warmAhead,startupTarget:this.options.startupBufferTarget,startupCommit:this.options.startupBufferCommit,startupMaxBytes:this.options.startupBufferMaxBytes,startupRecovery:i=>Math.max(this.options.originReserveMs,(Be(this.#W(i),.9)||0)*1.25+100),allowed:()=>this.#p()&&e.media?.paused!==!0&&!Ht(),next:i=>{let o=e.levels?.[i.frag?.level]?.details?.fragments;if(!Array.isArray(o))return[];let a=o.findIndex(l=>l.sn===i.frag.sn&&(l.cc??0)===(i.frag.cc??0));return a<0?[]:o.slice(a+1,a+3).map(l=>({url:l.url,frag:l,type:"media-fragment",headers:{},part:null,responseType:"arraybuffer",rangeStart:l.byteRangeStartOffset,rangeEnd:l.byteRangeEndOffset}))},authorise:async(i,o)=>{let a=await this.#C(i),l=await lt(d=>this.options.getCommitment(i,{signal:d}),o,1e3);if(o.aborted||this.stopped)return null;let c=d=>!this.stopped&&this.#ce(l,{streamEvent:this.options.streamEvent,swarmId:this.options.swarmId,key:a,context:d,maxSegmentBytes:this.options.maxSegmentBytes,delegation:this.options.delegation,revokedDelegationIds:this.options.revokedDelegationIds,delegationRevocations:this.options.delegationRevocations}),u=c(i);return u&&u.size<=this.options.maxHeldBytes?{...u,key:a,current:d=>{let p=c(d);return!!(p&&p.size===u.size&&p.sha256===u.sha256)}}:null},verify:async(i,o,a,l)=>o instanceof ArrayBuffer&&o.byteLength===i.size&&!l.aborted&&await Pt(o)===i.sha256,reserve:i=>(this.#ve(this.options.maxHeldBytes-i),!this.stopped&&this.heldBytes+i<=this.options.maxHeldBytes),reuseBudget:i=>{try{let o=e.media,a=o.currentTime,l=Math.max(this.options.originReserveMs,(Be(this.#W(i),.9)||0)*1.25+100);for(let c=0;ca)return Math.min(25,Math.max(0,(u-a)*1e3-l))}}catch{}return 0},onVerified:(i,o)=>(this.#nt(i.key),this.#L(i.key,new Uint8Array(o)),this.held.has(i.key)),onReuse:(i,o,a)=>{a>0&&i.frag&&this.peerFragments.add(i.frag)}}),e.config.fLoader=this.warmAhead.Loader;let r=e.media,s=()=>this.warmAhead?.clear();for(let i of["pause","ended"])r?.addEventListener?.(i,s,{signal:this.lifecycle.signal});r?.addEventListener?.("seeking",()=>{try{let i=r.currentTime;for(let o=0;o{r=o}),i=this.#h(pl,r);this.coreRelease=r,this.coreWait=s.then(()=>{clearTimeout(i),this.timers.delete(i),this.coreWait=null,this.coreRelease=null}),this.#n("core",()=>this.#ot().finally(r))}this.#n("start",()=>this.#ct()),typeof this.options.onMetrics=="function"&&this.#M(this.options.metricsIntervalMs,0,()=>this.options.onMetrics(this.metrics()))}catch(t){this.#o("attach",t)}}#t(e){let t=this,r=e.trigger;typeof r=="function"&&(this.originalTrigger=r,this.triggerWasOwn=Object.hasOwn(e,"trigger"),this.withheldTrigger=function(s,i){let o=(s==="hlsFragLoaded"||s==="hlsFragBuffered")&&i?.frag&&t.peerFragments.has(i.frag)?e.abrController?.bwEstimator:null;if(!o||typeof o.sample!="function"||typeof o.sampleTTFB!="function")return r.call(this,s,i);let a=()=>{t.counters.abrPeerSamplesWithheld+=1},l=["sample","sampleTTFB"].map(c=>[c,Object.getOwnPropertyDescriptor(o,c)]);o.sample=a,o.sampleTTFB=a;try{return r.call(this,s,i)}finally{for(let[c,u]of l)u?Object.defineProperty(o,c,u):delete o[c]}},e.trigger=this.withheldTrigger)}updateTicket(e){return this.stopped||this.disabledReason||!this.#G()||!ye(e)?!1:(e===this.options.ticket||(this.latePeerGeneration++,this.#a("ticket"),this.warmAhead?.clear(),this.options.ticket=e,this.#Be()),!0)}stop(){if(!this.stopped){this.stopped=!0,this.#a("stop"),this.uploadPacer?.stop(),this.warmAhead?.stop(),this.#q(),this.discovery.clear(),this.lifecycle.abort();for(let e of[...this.peerLeaseWaiters])e();this.peerLeases.clear(),this.transferWorker?.stop(),this.options.transferWorkerUrl!==void 0&&(this.transferWorkerState="stopped"),this.cachedRaces.clear(),this.admissionChecks.clear(),this.admitted.clear(),this.dialChecks.clear();for(let e of this.races)e.settled=!0,e.controller.abort();this.races.clear();try{this.hls&&this.hls.config.fLoader?.relayswarmShadow&&(this.hls.config.fLoader=this.originalFragmentLoader)}catch{}try{this.originalTrigger&&this.hls?.trigger===this.withheldTrigger&&(this.triggerWasOwn?this.hls.trigger=this.originalTrigger:delete this.hls.trigger)}catch{}this.originalTrigger=null;for(let e of this.timers)clearTimeout(e);this.timers.clear(),this.coreRelease?.();for(let e of this.haveWaiters)e();this.haveWaiters.clear();for(let e of this.dials.values()){this.#ie(e),this.#de(e.pc,"dial-end","host-stop");try{e.pc.close()}catch{}}this.dials.clear(),this.receivedOffers.clear();for(let e of[...this.links.values()])e.close("host-stop");this.links.clear(),this.held.clear(),this.heldBytes=0,this.originFetches.clear(),this.renditions.clear(),this.playerHints=[],this.hintSizes.clear(),this.hintOriginRates=[];try{this.session?.close()}catch{}try{this.pool?.close()}catch{}try{this.options.onMetrics?.(this.metrics())}catch{}}}trace(){return{v:1,capacity:this.options.traceRequests,dropped:this.traceDropped,rows:this.traceRows.map(e=>structuredClone(e))}}#e(e){if(this.options.traceRequests)try{this.traceRows.length>=this.options.traceRequests&&(this.traceRows.shift(),this.traceDropped=We(this.traceDropped)),this.traceRows.push(e)}catch{}}#s(e=I()){return Math.floor(e)-this.traceBase}#d(e){try{return(e&&this.traceLoads.get(e))??null}catch{return null}}#i(e,t,r,s){if(this.options.traceRequests)try{let i=this.traceLoadNext++;this.traceLoads.set(e,i);let o=a=>Number.isSafeInteger(a)?a:null;return this.#e({k:"load",load:i,at:this.#s(),sn:o(e.frag?.sn),level:o(e.frag?.level),cc:o(e.frag?.cc),budgetMs:Math.round(t),limitMs:Math.round(r),budgetGeometry:{...s}}),i}catch{}}#c(e,t,r){if(!this.options.traceRequests)return null;let s=I(),i=this.traceBase,o=!1,a=!1,l=!1,c=!1,u=g=>{let f=g;try{f??=r()}catch{}let m=b=>{try{let v=f?.[b];return Number.isSafeInteger(v)&&v>=0?v:null}catch{return null}};return{loaderLoadedBytes:m("loaded"),loaderTotalBytes:m("total")}},d=(g,f)=>this.#e({k:g,load:e,leg:t,at:this.#s(),ms:Math.round(I()-s),ranged:!1,...f});return d("originStart",{}),{progress:(g,f,m)=>{if(m){c||(c=!0,d("originCallback",{phase:"progress",outcome:null,stale:!0}));return}a||f!==!0||(a=!0,d("originProgress",{stale:!1,...u(g)}))},abortRequest:g=>{o||l||(l=!0,d("originAbortRequest",{reason:g,...u()}))},terminal:(g,f=null,m,b=!1)=>p(g,f,m,b)};function p(g,f,m,b){if(o){c||(c=!0,d("originCallback",{phase:"terminal",outcome:g,stale:!0}));return}o=!0;let v=b?{loaderLoadedBytes:null,loaderTotalBytes:null}:u(m);d("origin",{at:Math.floor(s)-i,outcome:g,bytes:Number.isSafeInteger(f)&&f>=0?f:null,stale:b,...v})}}peerConnections(){return this.peerConnectionDetails().map(e=>e.connection)}peerConnectionDetails(){let e=[];for(let t of this.links.values())try{!t.closed&&t.channel.readyState==="open"&&!["failed","closed","disconnected"].includes(t.pc.connectionState)&&e.push({connection:t.pc,pubkey:t.pubkey})}catch{}return e}metrics(){let e=this.counters,t=this.options.mode==="shadow",r=t?e.peerInTime+e.peerLate+e.peerMiss+e.peerCorrupt:0,s=r+e.noPeers,i=(o,a)=>a?Number((o/a).toFixed(3)):null;return{v:hl,swarmId:this.options.swarmId,mode:this.disabledReason?"off":this.options.mode,disabledReason:this.disabledReason||null,stopped:this.stopped,warmAhead:this.warmAhead?.snapshot()??null,startupBuffer:this.warmAhead?.startupSnapshot()??null,peerAdmission:{...this.peerAdmission,claimedLinks:this.peerLeases.size,waiting:this.peerLeaseWaiters.size},uploadPacing:this.uploadPacer?.snapshot()??null,latePeerRace:{enabled:this.options.latePeerRace,...this.latePeerCounts,pending:this.latePeerOwners.size,dropped:this.latePeerDropped,records:this.latePeerRows.map(o=>({...o,...o.holders?{holders:[...o.holders]}:{}})),limits:{windowMs:Math.min(4e3,this.options.lateWindowMs),peerMs:Math.min(2500,this.options.maxPeerWaitMs),owners:this.options.maxConcurrentRaces}},pubkey:this.session?.pubkey||null,uptimeMs:Date.now()-this.startedAt,serving:this.#p(),peers:{connected:this.links.size,dialling:this.dials.size,dialsStarted:e.dialsStarted,dialsAccepted:e.dialsAccepted,dialsFailed:e.dialsFailed,dialsTimedOut:e.dialsTimedOut,dialsRejected:e.dialsRejected,offersAccepted:e.offersAccepted,offersRefused:e.offersRefused,admitRefused:e.admitRefused,evicted:e.evicted,evictedUnhelpful:e.evictedUnhelpful,evictedServing:e.evictedServing,evictedConsumer:e.evictedConsumer,evictionsUnavailable:e.evictionsUnavailable,retriesScheduled:e.retriesScheduled,referralsSent:e.referralsSent,referralsFollowed:e.referralsFollowed,openPeersKnown:this.#_e().length,linksOpened:e.linksOpened,linksClosed:e.linksClosed,banned:this.banned.size,firstLinkAtMs:this.firstLinkAtMs,candidatePairs:{...this.pairTypes},deliveryMeasurements:[...this.links.values()].map(o=>({pubkey:o.pubkey,holder:this.#U(o.pubkey),...this.peerSelection.summary(o)}))},transportDiagnostics:{capacity:64,dropped:this.transportDropped,counters:Object.fromEntries(Object.entries(this.transportCounters).map(([o,a])=>[o,{...a}])),records:this.transportRecords.map(o=>({...o}))},neighbourDiscovery:this.discovery.snapshot(),...this.options.peerSupplyHint?{playerHint:structuredClone(this.playerHints)}:{},peerEligibilityDiagnostics:{capacity:64,dropped:this.peerEligibilityDropped,counters:{...this.peerEligibilityCounters},records:this.peerEligibilityRecords.map(o=>({...o,budgetGeometry:{...o.budgetGeometry},..."holders"in o?{holders:o.holders&&[...o.holders],haveHolders:o.haveHolders&&[...o.haveHolders],staleHolders:o.staleHolders&&[...o.staleHolders],heldMissHolders:o.heldMissHolders&&[...o.heldMissHolders]}:{},...o.projection?{projection:{...o.projection}}:{}}))},peerRequestDiagnostics:{capacity:64,dropped:this.peerRequestDropped,counters:{...this.peerRequestCounters},records:this.peerRequestRecords.map(o=>({...o}))},uploadRefusalDiagnostics:{counters:{...this.uploadRefusalCounters}},admissionDiagnostics:{calls:{...this.admissionCallCounters}},signalling:{samples:this.signallingSamples.length,medianMs:Be(this.signallingSamples,.5),p90Ms:Be(this.signallingSamples,.9),clock:{...this.session?this.session.clockDiagnostics():{aheadRejected:null,staleRejected:null,maxAheadSeconds:null,signalSamples:null,signalAgeMedianSeconds:null},origin:ss(this.originClockSamples)}},segments:{originLoaded:e.originLoaded,raced:e.raced,noPeers:e.noPeers,sampledOut:e.sampledOut,skipped:e.skipped,aborted:e.aborted,peerInTime:e.peerInTime,peerLate:e.peerLate,peerMiss:e.peerMiss,peerCorrupt:e.peerCorrupt,peerUnverified:e.peerUnverified,inTimeShare:i(e.peerInTime,r),sampledInTimeShare:i(e.peerInTime,s),observedInTimeShare:t?i(e.peerInTime,e.originLoaded):null,sampledInTimeByteShare:i(e.peerInTimeBytes,e.sampledOriginBytes),observedInTimeByteShare:t?i(e.peerInTimeBytes,e.bytesFromOrigin):null,peerFirstShare:t?null:i(e.peerFirstLoaded,e.peerFirstLoaded+e.originLoaded),peerFirstByteShare:t?null:i(e.peerFirstBytes,e.peerFirstBytes+e.bytesFromOrigin),peerFirstLoaded:e.peerFirstLoaded,zeroBudgetPeerRaces:e.zeroBudgetPeerRaces,zeroBudgetPeerRaceWins:e.zeroBudgetPeerRaceWins,abrPeerSamplesWithheld:e.abrPeerSamplesWithheld,originFallbacks:e.originFallbacks,coordinatedWaits:e.coordinatedWaits,coordinatedPeerLoads:e.coordinatedPeerLoads,peerSkippedLate:e.peerSkippedLate,peerProjectedLate:e.peerProjectedLate,peerWaitExtended:e.peerWaitExtended,peerAbandoned:e.peerAbandoned,peerNoFit:e.peerNoFit,peerUntestedTrial:e.peerUntestedTrial,peerUntestedTrialLoaded:e.peerUntestedTrialLoaded,commitmentRequests:e.commitmentRequests,commitmentRejected:e.commitmentRejected,commitmentUnavailable:e.commitmentUnavailable,firstPeerSegmentAtMs:this.firstPeerSegmentAtMs,peerLatencyMedianMs:Be(this.peerLatencySamples,.5),peerLatencyP90Ms:Be(this.peerLatencySamples,.9),originLatencyMedianMs:Be(this.originLatencySamples,.5)},bytes:{fromOrigin:e.bytesFromOrigin,fromPeers:e.bytesFromPeers,peerFirst:e.peerFirstBytes,uploaded:e.bytesUploaded,uploadsServed:e.uploadsServed,uploadsRefused:e.uploadsRefused,uploadsCancelled:e.uploadsCancelled,uploadCancelledBytes:e.uploadCancelledBytes,uploadRemaining:this.#H(),uploadExhausted:this.#H()===0,held:this.heldBytes},relays:{connected:this.pool?.sockets.length??0,presenceSent:e.presenceSent,signalsSent:e.signalsSent,published:this.pool?.published??0,rejected:this.pool?.rejected??0,rejectedTimestamp:this.pool?.rejectedTimestamp??0,sinceDropped:this.pool?.sinceDropped??0,publishErrors:e.publishErrors},errors:{total:e.errors,byStage:{...this.errorsByStage}},core:{state:this.coreState,verifier:this.coreVerifier?"wasm":"js",selection:this.peerSelection.kind??"js",discovery:this.discovery.kind??"js",links:{...this.coreLinks},fallbacks:this.coreFallbacks,decided:{...this.coreDecided},transferWorker:{...this.transferWorker?.snapshot()??{},state:this.transferWorkerState,reason:this.transferWorkerReason},multiHolder:{enabled:this.#A(),...this.multiHolder,originRangeOutcomes:{...this.originRangeOutcomes},timings:{durationMs:Qn(this.multiHolderTimings.map(o=>o[0])),slowestRequestMs:Qn(this.multiHolderTimings.map(o=>o[1])),requests:Qn(this.multiHolderTimings.map(o=>o[2]))}}},config:{originFallbackMs:this.options.originFallbackMs,maxPeerWaitMs:this.options.maxPeerWaitMs,originReserveMs:this.options.originReserveMs,sustainablePeerWait:this.options.sustainablePeerWait,zeroBudgetPeerRace:this.options.zeroBudgetPeerRace,lateHaveRace:this.options.lateHaveRace,lateWindowMs:this.options.lateWindowMs,maxPeers:this.options.maxPeers,maxUploadPeers:this.options.maxUploadPeers,maxUploadBytesPerSecond:this.options.maxUploadBytesPerSecond,maxUploadBytesPerSession:Number.isSafeInteger(this.options.maxUploadBytesPerSession)&&this.options.maxUploadBytesPerSession>=0?this.options.maxUploadBytesPerSession:null,serve:this.options.serve===!0,admit:typeof this.options.admit=="function",shadowSampleRate:this.options.shadowSampleRate,minLinkLifeMs:this.options.minLinkLifeMs,idleEvictMs:this.options.idleEvictMs,evictionCooldownMs:this.options.evictionCooldownMs,relays:Array.isArray(this.options.relays)?[...this.options.relays]:[]}}}#o(e,t){this.stopped||(this.counters.errors+=1,this.errorsByStage[e]=(this.errorsByStage[e]||0)+1)}#n(e,t){try{let r=t();r&&typeof r.catch=="function"&&r.catch(s=>this.#o(e,s))}catch(r){this.#o(e,r)}}#h(e,t){if(this.stopped)return null;let r=setTimeout(()=>{this.timers.delete(r),this.stopped||this.#n("timer",t)},Math.max(0,e));return this.timers.add(r),r}#M(e,t,r){let s=()=>{let i=e*t*(Math.random()*2-1);this.#h(e+i,()=>{try{r()}finally{s()}})};s()}#B(e,t){try{let r=ns(e,t);if(r===null)return;this.originClockSamples.push(r),this.originClockSamples.length>16&&this.originClockSamples.shift()}catch{}}#b(e){let t=this;return class{static relayswarmShadow=!0;constructor(s){this.inner=new e(s),this.hlsConfig=s,this.active=null,this.peerStats=null,this.peerContext=null,this.pendingCallbacks=null}get stats(){return this.peerStats||this.inner.stats}get context(){return this.peerContext||this.inner.context}load(s,i,o){this.abort(),this.releaseFetch=null,this.peerStats=null,this.originTrace=null,this.peerContext=s,s?.frag&&t.peerFragments.delete(s.frag);let a={source:"unobserved",positionSource:null,currentTime:null,bufferedEnd:null,playableEnd:null,fragmentStart:null,originReserveMs:null,uncappedMs:null},l=t.#Fe(s,a);if(t.#Y(s),t.options.peerSupplyHint&&t.#n("player-hint",()=>t.#R(s,l)),t.stopped||!s.frag||s.frag.sn==="initSegment"||s.part&&!t.options.swarmParts||!t.options.serveOnCellular&&Ht())return this.inner.load(s,i,o);if(l===0&&t.options.zeroBudgetPeerRace&&!this.hlsConfig.progressive&&t.#A()&&t.#l()){let A=new Map([...t.links.values()].filter(k=>t.#K(k,s)&&k.supportsRanges&&(t.remoteFraming.get(k.pubkey)??1)>=2&&!t.banned.has(k.pubkey)&&(k.have.size||t.options.lateHaveRace)).map(k=>[k,new Set(k.have)]));if(A.size)return this.loadCachedRace(s,i,o,a,A)}let c=i?.loadPolicy?.maxLoadTimeMs??i?.timeout;if(l===0&&t.options.latePeerRace&&!this.hlsConfig.progressive&&ve(s)&&Number.isFinite(c)&&c>0&&t.#l())return this.loadLatePeerRace(s,i,o,a,c);let u=new AbortController,d={};this.active=d;let p=I();Object.assign(this.inner.stats,{aborted:!1,loaded:0,total:0,chunkCount:0,bwEstimate:0,loading:{start:p,first:0,end:0},parsing:{start:0,end:0},buffering:{start:0,first:0,end:0}}),this.pendingCallbacks={callbacks:o,context:s};let g,f=null,m=()=>{clearTimeout(g),t.lifecycle.signal.removeEventListener("abort",b)};this.cancel=()=>{let A=this.active===d;return this.active=null,m(),u.abort(),A};let b=()=>{if(this.active!==d)return;this.active=null,this.pendingCallbacks=null,m(),u.abort(),t.counters.originFallbacks+=1,this.inner.stats.loading.start=0;let A=I(),k=!1,W=null,_=t.#C(s);_.then(h=>{!k&&!t.stopped&&(W=h,this.releaseFetch=t.#Z(h))}).catch(()=>{});let F=()=>k?!1:(k=!0,this.releaseFetch?.(),this.releaseFetch=null,!0),P=this.cancel;this.cancel=()=>(F(),P());let N=this.originTrace=t.#c(f,"fallback",()=>this.inner.stats);this.inner.load(s,i,{...o,onError:(...h)=>{N?.terminal("error",null,void 0,N!==this.originTrace),F(),o.onError?.(...h)},onTimeout:(...h)=>{N?.terminal("timeout",null,h[0],N!==this.originTrace),F(),o.onTimeout?.(...h)},onAbort:(...h)=>{N?.terminal("abort",null,h[0],N!==this.originTrace),F(),o.onAbort?.(...h)},onSuccess:(h,x,S,M)=>{if(k)return;let H=Vr(x),{copy:D,size:B}=t.#S(h,s);if(!k&&(W&&D&&t.#L(W,new Uint8Array(D)),!!F())){if(this.pendingCallbacks=null,N?.terminal("payload",B||null,x,N!==this.originTrace),je(t.originLatencySamples,I()-A),t.#X(t.renditionOriginSamples,s,I()-A),t.options.peerSupplyHint&&B){let U=t.#v(s);!t.hintSizes.has(U)&&t.hintSizes.size>=16&&t.hintSizes.delete(t.hintSizes.keys().next().value),t.hintSizes.set(U,B);let C=I()-A;C>0&&je(t.hintOriginRates,B/C)}o.onSuccess(h,x,S,M),t.#B(M,H),B&&!t.stopped&&t.#n("peer-first-origin",async()=>{if(t.counters.originLoaded+=1,t.counters.bytesFromOrigin+=B,!W){let U=await _;D&&!t.stopped&&t.#L(U,new Uint8Array(D))}})}}})};if(l===0)return f=t.#i(s,0,0,a),t.#E(s,l,"no-budget",null,a),b();let v=()=>{K.onDeadline?.()||(K.expired=!0,b())};g=setTimeout(v,l),t.lifecycle.signal.addEventListener("abort",b,{once:!0});let w=Math.max(t.options.originFallbackMs,t.options.maxPeerWaitMs),T=Math.max(l,Math.min(w,a.uncappedMs??l,a.sustainableMs??1/0));f=t.#i(s,l,T,a);let O={Loader:e,config:this.hlsConfig,loaderConfig:i},K={deadline:p+l,limit:p+T,originReserveMs:a.originReserveMs??t.options.originReserveMs,expired:!1,onDeadline:null,origin:O,extend:A=>{let k=Math.min(K.limit,A);return this.active!==d||k<=K.deadline?!1:(K.deadline=k,clearTimeout(g),g=setTimeout(v,Math.max(0,k-I())),!0)}};t.#ae(s,u.signal,K,l,a).then(A=>{if(!(this.active!==d||u.signal.aborted||t.stopped)){if(A&&!A.multi&&I()>=K.deadline&&t.#N(A.demand),!A||I()>=K.deadline&&!A.multi)return b();this.active=null,this.pendingCallbacks=null,m(),t.#O(this,A,s,o,p)}}).catch(A=>{this.active===d&&(t.#o("peer-first",A),b())})}loadCachedRace(s,i,o,a,l){let c=t.#i(s,0,t.options.maxPeerWaitMs,a),u={},d=new AbortController,p=I(),g=!0,f=!1,m=null,b,v;this.active=u,this.pendingCallbacks={callbacks:o,context:s},Object.assign(this.inner.stats,{aborted:!1,loaded:0,total:0,chunkCount:0,loading:{start:0,first:0,end:0}});let w=()=>{clearTimeout(v),t.lifecycle.signal.removeEventListener("abort",w),t.cachedRaces.delete(d),d.abort()};t.cachedRaces.add(d),t.lifecycle.signal.addEventListener("abort",w,{once:!0}),this.cancel=()=>{let A=g&&this.active===u;g=!1,this.active=null,w();try{this.inner.abort()}catch{}return A};let T=()=>!g||this.active!==u?!1:(g=!1,this.active=null,this.pendingCallbacks=null,w(),this.releaseFetch?.(),this.releaseFetch=null,!0);v=setTimeout(w,t.options.maxPeerWaitMs),t.counters.originFallbacks+=1,t.#E(s,0,"no-budget",null,a);let O=this.originTrace=t.#c(c,"cached",()=>this.inner.stats);try{this.inner.load(s,i,{...o,onProgress:(...A)=>{if(!g||this.active!==u){O?.progress(void 0,null,!0);return}let k=A[2]?.byteLength>0;k&&(f=!0,w()),O?.progress(A[0],k,!1),o.onProgress?.(...A)},onError:(...A)=>{O?.terminal("error",null,void 0,!g||this.active!==u),T()&&o.onError?.(...A)},onTimeout:(...A)=>{O?.terminal("timeout",null,A[0],!g||this.active!==u),T()&&o.onTimeout?.(...A)},onAbort:(...A)=>{O?.terminal("abort",null,A[0],!g||this.active!==u),T()&&o.onAbort?.(...A)},onSuccess:(A,k,W,_)=>{if((!g||this.active!==u)&&O?.terminal("payload",null,void 0,!0),!g||this.active!==u)return;let F=Vr(k),{copy:P,size:N}=t.#S(A,s);!g||this.active!==u||(m&&P&&t.#L(m,new Uint8Array(P)),T()&&(O?.terminal("payload",N||null,k),je(t.originLatencySamples,I()-p),t.#X(t.renditionOriginSamples,s,I()-p),o.onSuccess(A,k,W,_),t.#B(_,F),N&&!t.stopped&&t.#n("cached-race-origin",async()=>{if(t.counters.originLoaded+=1,t.counters.bytesFromOrigin+=N,!m){let h=await(b??t.#C(s));P&&!t.stopped&&t.#L(h,new Uint8Array(P))}})))}})}catch(A){throw T(),A}if(!g)return;b=t.#C(s),b.then(A=>{g&&!t.stopped&&(m=A,this.releaseFetch=t.#Z(A))}).catch(()=>{});let K={deadline:p+t.options.maxPeerWaitMs,limit:p+t.options.maxPeerWaitMs,originReserveMs:0,expired:!1,onDeadline:null,cachedOnly:l,lateHaveRace:t.options.lateHaveRace,peerOnly:!0,extend:()=>!1};t.#ae(s,d.signal,K,0,a).then(A=>{if(!(!A||!g||f||this.active!==u||d.signal.aborted||t.stopped||I()>=K.limit)){g=!1,this.active=null,this.pendingCallbacks=null,w(),this.releaseFetch?.(),this.releaseFetch=null,O?.abortRequest("peer-won");try{this.inner.abort()}catch{}t.counters.zeroBudgetPeerRaceWins+=1,t.#O(this,A,s,o,p)}}).catch(A=>{g&&!d.signal.aborted&&!t.stopped&&t.#o("cached-race",A)}).finally(w)}loadLatePeerRace(s,i,o,a,l){let c=t.#i(s,0,l,a),u={},d=new AbortController,p=I(),g=!0,f=!1,m=null,b;this.active=u,this.pendingCallbacks={callbacks:o,context:s},Object.assign(this.inner.stats,{aborted:!1,loaded:0,total:0,chunkCount:0,loading:{start:0,first:0,end:0}});let v=()=>g&&!f&&this.active===u&&!t.stopped,w=O=>!g||this.active!==u?!1:(g=!1,this.active=null,this.pendingCallbacks=null,b?.close(O),this.releaseFetch?.(),this.releaseFetch=null,!0);this.cancel=()=>{let O=g&&this.active===u;g=!1,this.active=null,b?.close("caller-abort"),this.releaseFetch?.(),this.releaseFetch=null;try{this.inner.abort()}catch{}return O};let T;b=t.#w({context:s,controller:d,entryAt:p,parentDeadline:p+l,current:v,arm:(O,K)=>(t.options.traceRequests&&t.traceLoads.set(O,c),t.#ae(O,d.signal,K,0,a).then(A=>{if(!A||!v()||d.signal.aborted||I()>=K.limit||!b.valid()||typeof K.revalidateAuthority!="function"||!K.revalidateAuthority())return!1;g=!1,this.active=null,this.pendingCallbacks=null,b.close("peer-won","won"),this.releaseFetch?.(),this.releaseFetch=null,T?.abortRequest("peer-won");try{this.inner.abort()}catch{}return t.counters.zeroBudgetPeerRaceWins++,t.#O(this,A,s,o,p),!0}))}),t.counters.originFallbacks++,t.#E(s,0,"no-budget",null,a),T=this.originTrace=t.#c(c,"late",()=>this.inner.stats);try{this.inner.load(s,i,{...o,onProgress:(...O)=>{if(!g||this.active!==u){T?.progress(void 0,null,!0);return}let K=O[2]?.byteLength>0;K&&(f=!0,b?.close("origin-progress")),T?.progress(O[0],K,!1),o.onProgress?.(...O)},onError:(...O)=>{T?.terminal("error",null,void 0,!g||this.active!==u),w("origin-error")&&o.onError?.(...O)},onTimeout:(...O)=>{T?.terminal("timeout",null,O[0],!g||this.active!==u),w("origin-timeout")&&o.onTimeout?.(...O)},onAbort:(...O)=>{T?.terminal("abort",null,O[0],!g||this.active!==u),w("origin-abort")&&o.onAbort?.(...O)},onSuccess:(O,K,A,k)=>{if((!g||this.active!==u)&&T?.terminal("payload",null,void 0,!0),!g||this.active!==u)return;let W=Vr(K),{copy:_,size:F}=t.#S(O,s);!g||this.active!==u||(m&&_&&t.#L(m,new Uint8Array(_)),w("origin-success")&&(T?.terminal("payload",F||null,K),je(t.originLatencySamples,I()-p),t.#X(t.renditionOriginSamples,s,I()-p),o.onSuccess(O,K,A,k),t.#B(k,W),F&&!t.stopped&&t.#n("late-race-origin",async()=>{if(t.counters.originLoaded++,t.counters.bytesFromOrigin+=F,!m){let P=await(b?.keyPromise??t.#C(s));_&&!t.stopped&&t.#L(P,new Uint8Array(_))}})))}})}catch(O){throw w("origin-throw"),O}g&&b?.keyPromise.then(O=>{g&&this.active===u&&!t.stopped&&(m=O,this.releaseFetch=t.#Z(O))}).catch(()=>{})}abort(){if(this.originTrace?.abortRequest("caller-abort"),this.releaseFetch?.(),this.releaseFetch=null,this.cancel?.()&&this.pendingCallbacks){let{callbacks:i,context:o}=this.pendingCallbacks;this.pendingCallbacks=null,this.inner.stats.aborted=!0,t.counters.aborted+=1,i.onAbort?.(this.inner.stats,o,null)}else this.inner.abort()}destroy(){let s;try{let i=this.peerStats;i?.aborted===!1&&(s=i)}catch{}try{this.originTrace?.abortRequest("destroy"),this.releaseFetch?.(),this.releaseFetch=null,this.cancel?.(),this.pendingCallbacks=null,this.inner.destroy()}finally{try{s&&s.aborted!==!1&&(s.aborted=!1)}catch{}}}getCacheAge(){return this.peerStats?null:this.inner.getCacheAge?.()??null}getResponseHeader(s){return this.peerStats?null:this.inner.getResponseHeader?.(s)??null}}}#S(e,t){try{let r=e.data,s=r?.byteLength;return s?{copy:this.#xe()&&!t?.[ke]?r.slice(0):null,size:s}:{copy:null,size:0}}catch{return{copy:null,size:0}}}#l(){return this.cachedRaces.size+[...this.latePeerOwners.values()].filter(e=>!e.attempted).lengtha===null?null:Math.max(0,Math.round(a-this.transportStartedAt));this.latePeerRows.push({id:e.id,atMs:o(I()),sequence:i.sn,cc:i.cc,level:i.level,genuineAtMs:o(e.genuineAt),windowEndAtMs:o(e.windowEnd),armedAtMs:o(e.armedAt??null),deadlineAtMs:o(e.peerLimit??null),outcome:t,reason:r,...e.dependencyAt!==null?{startupDependencyAtMs:o(e.dependencyAt),startupDeadlineAtMs:o(e.dependencyDeadline)}:{},...s?{holders:s.map(a=>this.#U(a.pubkey))}:{}})}#a(e){for(let t of[...this.latePeerOwners.values()])t.close(e)}#k(){for(let e of[...this.latePeerOwners.values()])e.refresh()}#w(e){let t=ve(e.context);if(!t||!this.#l())return null;let r=e.context[ke],s=e.entryAt,i=this.hls?.media,o={...e,identity:t,id:this.latePeerNextId++,generation:this.latePeerGeneration,streamId:this.options.streamEvent?.id,genuineAt:null,dependencyAt:null,dependencyDeadline:null,windowEnd:null,attempted:!1,closed:!1,key:null,timer:null},a=new AbortController,l=()=>{clearTimeout(o.timer),this.timers.delete(o.timer),o.timer=null};o.close=(p,g="retired")=>{o.closed||(o.closed=!0,l(),a.abort(),r?.onGenuine===o.refresh&&delete r.onGenuine,this.latePeerOwners.delete(o.id),this.cachedRaces.delete(o.controller),o.controller.abort(),this.#f(o,g,p))};let c=()=>{let p=r?r.genuine?.():{at:s,context:e.context};if(p)return{...p,role:"genuine"};let g=r?.startupDependency?.();return g&&Number.isFinite(g.at)&&Number.isFinite(g.deadline)&&g.signal?.aborted===!1?{...g,role:"startup-buffer-dependency"}:null},u=(p,g)=>this.links.get(p.pubkey)===p&&this.#K(p,g)&&p.supportsRanges===!0&&(this.remoteFraming.get(p.pubkey)??1)>=2&&!this.banned.has(p.pubkey)&&p.have.has(o.key),d=()=>{let p=c();return!p||!Number.isFinite(p.at)||ve(p.context)?.key!==t.key?null:r?{...p.context,[ke]:r}:p.context};o.valid=()=>!o.closed&&e.current()&&!this.stopped&&o.generation===this.latePeerGeneration&&o.streamId===this.options.streamEvent?.id&&d()!==null&&!i?.paused&&!i?.ended&&I()<(o.peerLimit??o.windowEnd??e.parentDeadline)&&[...o.validatedPeers??[]].every(([p,g])=>this.links.get(p.pubkey)===p&&!p.closed&&!this.banned.has(p.pubkey)&&(!this.options.admit||this.admitted.get(p.pubkey)?.ticket===g)),o.refresh=()=>{if(o.closed)return;if(!e.current()||this.stopped||o.generation!==this.latePeerGeneration||o.streamId!==this.options.streamEvent?.id)return o.close("inactive");let p=c();if(!p){o.windowEnd!==null&&o.close(o.dependencyAt!==null?"startup-buffer-ended":"no-genuine-consumer");return}let g=d();if(!g||i?.paused||i?.ended)return o.close("context-or-playback");if(o.windowEnd===null){let b=p.role==="startup-buffer-dependency";o.genuineAt=b?null:p.at,o.dependencyAt=b?s:null,o.dependencyDeadline=b?p.deadline:null,o.windowEnd=Math.min(e.parentDeadline,b?p.deadline:1/0,(b?s:p.at)+Math.min(4e3,this.options.lateWindowMs)),b&&p.signal.addEventListener("abort",()=>o.close("startup-buffer-ended"),{once:!0,signal:a.signal}),this.#f(o,"entered",b?"startup-buffer-dependency":"genuine-demand"),o.timer=this.#h(Math.max(0,o.windowEnd-I()),()=>o.close("window-expired","expired"))}else p.role==="genuine"&&o.genuineAt===null&&(o.genuineAt=p.at);if(I()>=o.windowEnd)return o.close("window-expired","expired");if(o.attempted||!o.key||!this.#A())return;let f=[...this.links.values()].filter(b=>u(b,g));if(!f.length)return;o.attempted=!0;let m=Math.min(o.windowEnd,I()+Math.min(2500,this.options.maxPeerWaitMs),e.parentDeadline);o.armedAt=I(),o.peerLimit=m,l(),o.timer=this.#h(Math.max(0,m-I()),()=>o.close("peer-expired","expired")),this.cachedRaces.add(o.controller),this.#f(o,"armed","accepted-exact-have",f),(async()=>{let b=await Promise.all(f.map(async A=>{if(!this.options.admit)return A;let k=this.admissionChecks.get(A.pubkey)?.ticket??this.admitted.get(A.pubkey)?.ticket,W=!1;try{W=await lt(()=>this.#x(A.pubkey,k,"other"),o.controller.signal,Math.max(0,Math.min(this.options.admissionTimeoutMs,m-I())))===!0}catch{}return!W&&!o.closed&&A.close("admission"),W?A:null}));if(o.closed)return;let v=d();if(!e.current()||!v||I()>=m||o.generation!==this.latePeerGeneration)return o.close("inactive-after-admission");let w=b.filter(A=>A&&u(A,v));if(!w.length)return o.close("admission-or-have-refused","refused");o.validatedPeers=new Map(w.map(A=>[A,this.admitted.get(A.pubkey)?.ticket]));let T=ve(v)?.context;if(!T||!o.valid())return o.close("context-after-admission");let O={deadline:m,limit:m,originReserveMs:0,expired:!1,onDeadline:null,knownKey:o.key,cachedOnly:new Map(w.map(A=>[A,new Set([o.key])])),lateHaveRace:!1,peerOnly:!0,extend:()=>!1,currentValid:o.valid,revalidateAuthority:!0};!await e.arm(T,O)&&!o.closed&&o.close("peer-no-result","refused")})().catch(()=>{o.closed||o.close("peer-error","refused")})},this.latePeerOwners.set(o.id,o),r&&(r.onGenuine=o.refresh);for(let p of["pause","ended","emptied"])i?.addEventListener?.(p,()=>o.close(`media-${p}`),{signal:a.signal});return o.keyPromise=this.#C(e.context).then(p=>(o.key=p,o.closed||o.refresh(),p),p=>{throw o.close("key-refused","refused"),p}),o.keyPromise.catch(()=>{}),o.refresh(),o}#O(e,t,r,s,i){let o=I(),a=t.bytes.byteLength;e.peerStats=e.inner.stats,Object.assign(e.peerStats,{aborted:!1,loaded:a,total:a,chunkCount:1,bwEstimate:a*8e3/Math.max(1,o-i),loading:{start:i,first:o,end:o},parsing:{start:0,end:0},buffering:{start:0,first:0,end:0}});let l=t.multi?t.peerBytes:a;if(this.counters.bytesFromPeers+=l,l>0)if(t.multi){let p=new Map(t.contributions.filter(f=>f.bytes>0).map(f=>[f.connection,f.bytes])),g=new Map((t.shortRefreshes||[]).map(f=>[f.connection,f.at]));for(let f of this.links.values())p.has(f.pc)&&this.#pe(f,p.get(f.pc),g.get(f.pc))}else{let p=this.links.get(t.pubkey);p?.pc===t.connection&&this.#pe(p,a)}let c=p=>{if(l>0&&(this.counters.peerFirstLoaded+=1),this.counters.peerFirstBytes+=l,l>0){if(!t.multi)this.discovery.holderDelivered(t.holderContext,t.pubkey);else{let g=new Map(t.contributions.filter(f=>f.bytes>0).map(f=>[f.connection,f.bytes]));for(let f of this.links.values())g.has(f.pc)&&this.discovery.holderDelivered(t.holderContext,f.pubkey)}this.discovery.verified(t.discoveryContext)&&this.discovery.window?.context===t.discoveryContext&&this.#q(),this.firstPeerSegmentAtMs===null&&(this.firstPeerSegmentAtMs=Date.now()-this.startedAt),je(this.peerLatencySamples,o-i),p.frag&&this.peerFragments.add(p.frag)}},u=()=>{if(typeof this.options.onPeerDelivery=="function"){let p=t.multi?t.contributions:[{connection:t.connection,bytes:a}];for(let{connection:g,bytes:f}of p)if(!(f<=0))try{let m=this.options.onPeerDelivery({connection:g,bytes:f});m&&typeof m.then=="function"&&Promise.resolve(m).catch(()=>{})}catch{}}},d=p=>{c(p),u()};r[ke]?Object.assign(r[ke],{peerBytes:l,accept:d,commit:c,notify:u}):d(r),!r[ke]&&this.#p()&&!this.held.has(t.key)&&this.#L(t.key,t.bytes.slice()),s.onSuccess({url:r.url,data:t.bytes.buffer,code:200},e.peerStats,r,null)}async#R(e,t){if(!e?.frag||e.frag.sn==="initSegment"||e.part||this.stopped)return;let r=++this.hintGeneration,s=this.hls?.levels||[],i=s.length?s.map((a,l)=>{if(l===e.frag.level)return e;let c=a.details?.fragments?.find(u=>u.sn===e.frag.sn&&u.cc===e.frag.cc);return c?{url:c.url,frag:c,rangeStart:c.byteRangeStartOffset,rangeEnd:c.byteRangeEndOffset}:null}):[e],o=await Promise.all(i.map(async(a,l)=>{let c=a?this.#v(a):`main:${l}`,u=a?await this.#C(a):null;if(this.stopped||r!==this.hintGeneration)return null;let d=a&&this.discovery.contexts.get(a.frag.type||"main"),p=u?[...this.links.values()].filter(T=>this.#P(T)&&T.have.has(u)&&T.supportsRanges===!0&&(this.remoteFraming.get(T.pubkey)??1)>=2&&!this.banned.has(T.pubkey)&&!(d?.rendition===c&&this.discovery.stale(d,T.pubkey))).map((T,O)=>{let K=this.peerSelection.summary(T).throughputBytesPerSecond;return[O+1,null,K?K/1e3:null]}):[],g=a?this.renditionSizes.get(c)??this.hintSizes.get(c)??null:null,f=a?Math.ceil((s[l]?.bitrate??0)*(a.frag.duration??0)/8):0,m=g??(f>0&&f<=this.options.maxSegmentBytes?f:null),b=Be(this.renditionOriginSamples.get(c)||[],.5),v={rendition:c,size:m,peers:p,origin:[null,m&&b?m/b:Be(this.hintOriginRates,.5)],sharedFirstByteMs:this.peerSelection.firstByteMs(),sharedRate:this.peerSelection.rate(),availableMs:t,maxHolders:this.options.maxHoldersPerObject},w=this.core?.playerHint(v);return w&&this.options.traceRequests&&this.#e({k:"playerHint",at:this.#s(),input:v,out:w}),w?{...w,level:a?.frag.level??l,sequence:a?.frag.sn??null,sizeEstimate:m,sizeEstimateSource:g!==null?"observed":m!==null?"playlist-bitrate":null,knowledge:"linked-have"}:null}));this.stopped||r!==this.hintGeneration||(this.playerHints=o.filter(Boolean),this.playerHints.length&&this.options.onPlayerHint?.(structuredClone(this.playerHints)))}#v(e){let t=Ot(e);return t?`${t.mediaType}:${t.playlist}`:`${e.frag.type||"main"}:${e.frag.level}`}#Y(e){if(this.stopped||!e.frag||e.frag.sn==="initSegment"||this.coreWait)return;let t=this.#v(e);if(this.latePeerOwners.size&&e.frag.type==="main"){let s=ve(e)?.scope;if(s)for(let i of[...this.latePeerOwners.values()])i.identity.scope!==s&&i.close("rendition")}this.discovery.context(e.frag.type||"main",t),this.#j(!1);let r=this.renditions.get(t);for(let[s,i]of this.renditions)i=8&&this.renditions.delete(this.renditions.keys().next().value),this.renditions.set(t,Date.now()),this.rendition=t,!r)for(let s of this.links.values())s.sendContribution(this.#p(),t)}#I(e,t,r){let s=Date.now(),i=[...this.links.values()].filter(l=>!l.closed&&l.contribution?.serving&&(l.renditions.get(t)||0)>s-3e4);if(!i.length)return!1;if(i.some(l=>(l.fetching.get(e)||0)>s))return!0;let o=r?.frag;if(o?.type==="main"&&Number.isInteger(o.level)&&o.level>=0&&this.hls?.levels?.[o.level]?.details?.live===!1)return!1;if(!this.#p())return!0;let a=l=>[...l].map((c,u)=>(parseInt(c,16)^parseInt(e[u],16)).toString(16)).join("");return i.some(l=>a(l.pubkey)=this.options.maxConcurrentRaces)return()=>{};let t=this.originFetches.get(e)||0;this.originFetches.set(e,t+1);for(let s of this.links.values())s.sendFetching(e,2e3);let r=!1;return()=>{if(r)return;r=!0;let s=(this.originFetches.get(e)||1)-1;if(s>0)this.originFetches.set(e,s);else{this.originFetches.delete(e);for(let i of this.links.values())i.sendFetching(e,0)}}}#Fe(e,t){if(e?.[ke])return t.source="warm-ahead",0;let r=this.hls?.media,s=1/0;if(this.options.sustainablePeerWait){let i=null;try{let l=e?.part,c=l?l.duration:e?.frag?.duration;Number.isFinite(c)&&c>0&&Number.isFinite(c*1e3)&&(i=c*1e3)}catch{}let o=Be(this.#W(e),.9),a=o===null?null:o*1.25+100;s=i===null||a===null?0:Math.max(0,i-a),Object.assign(t,{durationMs:i,originRecoveryMs:a,sustainableMs:s})}if(!r)return t.source="no-media",Math.min(this.options.originFallbackMs,s);try{for(let i=0;ir.currentTime){let o=Math.max(this.options.originReserveMs,(Be(this.#W(e),.9)||0)*1.25+100),a,l,c,u=(a=e?.part?.start)??e?.frag?.start,d=Number.isFinite(u)&&u>r.currentTime?Math.min(l=r.buffered.end(i),u):l=r.buffered.end(i),p=Math.max(0,(d-(c=r.currentTime))*1e3-o),g=Math.min(this.options.originFallbackMs,p,s);try{let f=m=>Number.isFinite(m)?m:null;Object.assign(t,{source:"buffer",positionSource:a==null?"fragment":"part",currentTime:f(c),bufferedEnd:f(l),playableEnd:f(d),fragmentStart:f(u),originReserveMs:f(o),uncappedMs:f(p)})}catch{}return g}}catch{return t.source="error",0}return t.source="no-buffer",0}async#C(e){let t=(this.options.segmentKey||to)(e.url||e.frag.url,e);if(typeof t!="string"||!t)throw new Error("Invalid segment key.");let r=e.rangeEnd?`#${e.rangeStart||0}-${e.rangeEnd}`:"";return Pt(eo.encode(`${this.options.swarmId} -${t}${r}`))}#qe(e){if(this.holderLabels.has(e)||(this.holderLabels.set(e,this.holderLabelNext++),this.holderLabels.size<=64))return;let t=[...this.holderLabels.keys()].find(r=>!this.links.has(r))??this.holderLabels.keys().next().value;this.holderLabels.delete(t)}#U(e){return this.holderLabels.get(e)??0}#je({key:e,rendition:t,context:r}){let s=l=>l.sort((c,u)=>c-u).slice(0,8),i=[],o=[],a=[];for(let l of this.links.values()){let c=this.#U(l.pubkey);this.#F(l,t)&&(i.push(c),this.discovery.stale(r,l.pubkey)&&a.push(c)),l.have.has(e)&&o.push(c)}return{holders:s(i),haveHolders:s(o),staleHolders:s(a),heldMissHolders:[]}}#N(e,{everyServing:t=!1,unfit:r=[]}={}){let{key:s,rendition:i,context:o}=e;if(!(!o||e.recorded)){e.recorded=!0;try{let a=[...this.links.values()].filter(u=>this.#F(u,i));if(t&&![...this.links.values()].some(u=>u.have.has(s))){for(let u of a)this.discovery.holderMiss(o,u.pubkey,s);return}let l=a.filter(u=>e.asked.has(u.pubkey)||r.includes(u.pubkey)),c=[];for(let u of l)this.discovery.holderMiss(o,u.pubkey,s)&&(this.discovery.counters.heldMiss++,c.push(this.#U(u.pubkey)));c.length&&e.row?.heldMissHolders&&(e.row.heldMissHolders=c.sort((u,d)=>u-d).slice(0,8))}catch{}}}#We(e,t){this.stopped||this.options.mode!=="peer-first"||this.discovery.counters.checks!==t||!this.discovery.current(e)||!this.#he(e)||!this.#Re(e)||this.discovery.hinted(e,r=>this.#Te(r))&&this.discovery.counters.staleBlocked++}#E(e,t,r,s,i,o,a,l=!1,c){try{if(!ro.includes(r))return;let u=m=>Number.isSafeInteger(m)&&m>=0?m:null,d=null,p=null;try{d=u(e?.frag?.cc)}catch{}try{p=u(e?.frag?.level)}catch{}let g=I()-this.transportStartedAt,f={atMs:Number.isFinite(g)?Math.max(0,Math.round(g)):0,cc:d,level:p,budgetMs:Number.isFinite(t)&&t>=0?t:null,reason:r,matchingHave:typeof s=="boolean"?s:null,budgetGeometry:{...i}};if(o&&(f.projection={...o}),l===!0&&(f.trial=!0),a){try{Object.assign(f,this.#je(a))}catch{Object.assign(f,{holders:null,haveHolders:null,staleHolders:null,heldMissHolders:null})}a.row=f}this.peerEligibilityCounters[r]=We(this.peerEligibilityCounters[r]),this.peerEligibilityRecords.length===64&&(this.peerEligibilityRecords.shift(),this.peerEligibilityDropped=We(this.peerEligibilityDropped)),this.peerEligibilityRecords.push(f),this.options.traceRequests&&this.#e({k:"eligibility",load:c===void 0?this.#d(e):c,at:this.#s(),...structuredClone(f)})}catch{}}#X(e,t,r){let s=this.#v(t);!e.has(s)&&e.size>=16&&e.delete(e.keys().next().value);let i=e.get(s)||[];je(i,r),e.set(s,i)}#W(e){try{let t=e?.frag&&this.renditionOriginSamples.get(this.#v(e));return t?.length?t:this.originLatencySamples}catch{return this.originLatencySamples}}#Ke(e,t,r,s){if(!(t>0)||!Number.isFinite(t)||rXn&&o.firstBytes.shift();let l=s-r;l>=Wr&&i>=Kr&&(o.flows.push({value:Math.min(1e6,i/l),flowMs:l,at:a}),o.flows.length>Xn&&o.flows.shift())}#pe(e,t,r=null){if(!e||e.closed||!Number.isSafeInteger(t)||t<=0)return;let s=this.#J(e);Number.isFinite(r)&&(s.flows=s.flows.filter(i=>i.at>=r)),s.usefulAt=I()}#$e(e,t,r){let s=this.#J(e),i=I();s.firstBytes=s.firstBytes.filter(d=>i-d.at<=Jn),s.flows=s.flows.filter(d=>i-d.at<=Jn);let o=s.firstBytes.reduce((d,p)=>d===null?p.value:(d+p.value)/2,null),a=s.flows.filter(d=>d.flowMs>=(o??0)*3),l=ml((a.length>=2?a:s.flows).map(d=>d.value),.75),c=l!==null&&(o??0)+r/l<=t,u=l===null&&(o??0)=ul)return{state:s,firstByteMs:null,rate:null,refresh:!0};if(l===null)return null}return{state:s,firstByteMs:o,rate:l,refresh:!1}}#Ge(e,t){let r=Be(this.renditionOriginSamples.get(t)||[],.5);if(r===null)return null;let s=null;for(let i of this.links.values()){let o=i.fetching.get(e)||0;o>Date.now()&&(s=Math.min(s??1/0,o-2e3))}return Math.max(0,r-(s===null?0:Date.now()-s))}#ge(e,t,r){let s=r.limit-I(),i=this.peerSelection.firstByteMs();if(t!==null&&t+(i??0)>s)return"late";if(e===null||t===null)return"unknown";let o=t+e;return o<=s?"fits":Date.now()-this.peerSelection.lastObservedAt>=yl?"stretch":o>s*1.25?"late":"stretch"}#me(e,t,r){let s=e==="fits"?I()+t*1.25+100:e==="stretch"?r.limit:null;s!==null&&r.extend(s)&&(this.counters.peerWaitExtended+=1)}#Q(e,t,r,s){let i=a=>Number.isFinite(a)?Math.round(a):null,o=this.peerSelection.rate();return{stage:e,transferMs:i(t),holderWaitMs:i(r),roomMs:i(s.limit-I()),firstByteMs:i(this.peerSelection.firstByteMs()),rateBytesPerSecond:Number.isFinite(o)?Math.round(o*1e3):null}}#ye(e,t){for(let r of this.links.values())if(!(!this.#P(r)||this.banned.has(r.pubkey)||!r.have.has(e))&&this.peerSelection.summary(r).attempts===0&&!(t&&this.discovery.stale(t,r.pubkey)))return r;return null}#be(e,t){return t.limit-I()>(this.peerSelection.firstByteMs()??0)&&!!this.#ye(e.key,e.context)}async#ae(e,t,r,s,i){let o=this.options.traceRequests?this.#d(e):null,a=r.deadline;if(this.options.transferWorkerUrl!==void 0&&this.transferWorkerState!=="ready")return null;let l=this.discovery.contexts.get(e.frag.type||"main"),c=r.knownKey??await this.#C(e);if(t.aborted||this.stopped||r.currentValid&&!r.currentValid())return this.#E(e,s,"aborted-before-eligibility",null,i,void 0,void 0,!1,o),null;if(r.cachedOnly){let P=h=>[...r.cachedOnly].filter(([x,S])=>(!h||S.has(c))&&x.have.has(c)&&this.links.get(x.pubkey)===x&&this.#K(x,e)&&!this.banned.has(x.pubkey)&&x.supportsRanges===!0&&(this.remoteFraming.get(x.pubkey)??1)>=2).map(([x])=>x),N=P(!0);if(!N.length&&r.lateHaveRace){for(N=P(!1);!N.length&&!t.aborted&&!this.stopped&&I()0}if(t.aborted||this.stopped||I()>=r.limit||(r.cachedHolders=new Set(N),!r.cachedHolders.size||!this.#A()))return null;this.counters.zeroBudgetPeerRaces+=1}let u=this.#v(e),d=l?.rendition===u&&this.discovery.contexts.get(l.mediaType)===l?l:null;if(d&&!r.cachedOnly){this.discovery.demand(l.mediaType,u,c);let P=this.discovery.counters.checks;this.#re();try{this.#We(d,P)}catch{}}let p={key:c,rendition:u,context:d,recorded:!1,asked:new Set,row:null},g=![...this.links.values()].some(P=>P.have.has(c));if(g&&!this.#I(c,u,e))return this.#E(e,s,"no-have-no-wait",!1,i,void 0,p,!1,o),null;let f=this.renditionSizes.get(u),m=g?this.#Ge(c,u):0,b=f?this.peerSelection.projectMs(f):null,v=!g&&this.#A()&&[...this.links.values()].some(P=>this.#K(P,e)&&P.supportsRanges===!0&&P.have.has(c)&&!this.banned.has(P.pubkey)&&(this.remoteFraming.get(P.pubkey)??1)>=2&&!(d&&this.discovery.stale(d,P.pubkey))),w=r.cachedOnly||v?"unknown":this.#ge(b,m,r),T=null;if(w==="late"&&!g&&this.#be(p,r)&&(T=this.#Q("entry",b,m,r),w="stretch"),w==="late")return this.#E(e,s,"projected-late",!g,i,this.#Q("entry",b,m,r),p,!1,o),this.#N(p,{everyServing:!0}),this.counters.peerProjectedLate+=1,null;this.#me(w,m+b,r),g&&(this.#E(e,s,"no-have-wait",!1,i,void 0,p,!1,o),this.counters.coordinatedWaits+=1);let O=r.deadline-I();if(t.aborted||this.stopped||O<=0)return null;this.counters.commitmentRequests+=1;let K=lt(P=>{if(t.aborted||this.stopped||I()>=r.deadline)throw new Error("Commitment load no longer active.");return this.options.getCommitment(e,{signal:P})},t,O).then(P=>({ok:!0,event:P}),()=>({ok:!1}));if(g){for(;!t.aborted&&!this.stopped&&I()N.have.has(c));){if(!this.#I(c,u,e))return this.#E(e,s,"wait-no-longer-eligible",!1,i,void 0,p,!1,o),null;await this.#ee(c,Math.min(100,r.deadline-I()),t)}let P=t.aborted||this.stopped;if(P||I()>=r.deadline)return this.#E(e,s,P?"wait-aborted":"wait-expired",null,i,void 0,p,!1,o),(!P||r.expired&&!this.stopped)&&this.#N(p,{everyServing:!0}),null}this.#E(e,s,g||r.lateHaveMatched?"have-after-wait":"have-at-entry",!0,i,T??void 0,p,T!==null,o);let A,k;try{let P=await K;if(!P.ok)throw new Error("Commitment unavailable.");k=P.event,A=this.#ce(P.event,{streamEvent:this.options.streamEvent,swarmId:this.options.swarmId,key:c,context:e,maxSegmentBytes:this.options.maxSegmentBytes,delegation:this.options.delegation,revokedDelegationIds:this.options.revokedDelegationIds,delegationRevocations:this.options.delegationRevocations})}catch{return this.stopped||(this.counters.commitmentUnavailable+=1),null}if(!A)return this.counters.commitmentRejected+=1,null;if(r.currentValid&&!r.currentValid()||(r.revalidateAuthority===!0&&(r.revalidateAuthority=()=>!!this.#ce(k,{streamEvent:this.options.streamEvent,swarmId:this.options.swarmId,key:c,context:e,maxSegmentBytes:this.options.maxSegmentBytes,delegation:this.options.delegation,revokedDelegationIds:this.options.revokedDelegationIds,delegationRevocations:this.options.delegationRevocations})),t.aborted||this.stopped)||r.cachedOnly&&A.v!==3)return null;if(!this.renditionSizes.has(u)&&this.renditionSizes.size>=16&&this.renditionSizes.delete(this.renditionSizes.keys().next().value),this.renditionSizes.set(u,A.size),A.v===3&&this.options.multiHolder){let P=await this.#Xe(e,t,r,c,A,l,o);if(P!==void 0)return P&&g&&(this.counters.coordinatedPeerLoads+=1),P&&{...P,holderContext:d}}if(r.cachedOnly)return null;let W=this.peerSelection.projectMs(A.size),_=this.#ge(W,0,r);if(_==="late"&&!g&&(T!==null||this.#be(p,r))&&(T=this.#Q("commitment",W,0,r),_="stretch",p.row&&(p.row.projection={...T},p.row.trial=!0)),_==="late")return this.#E(e,s,"projected-late",!0,i,this.#Q("commitment",W,0,r),p,!1,o),this.counters.peerProjectedLate+=1,null;this.#me(_,W,r);let F=new Set;for(;!t.aborted&&!this.stopped&&I()P||(N??0)>P)return this.counters.peerSkippedLate+=1,null;let h=($,ne)=>this.peerSelection.estimate($,A.size)===null||this.peerSelection.estimate($,A.size)*1.25+25<=ne,x=T&&F.size===0?this.#ye(c,p.context):null;x&&this.peerSelection.markSelected(x);let S=x??this.peerSelection.select([...this.links.values()].filter($=>this.#P($)),c,F,A.size,P);if(!S){if(![...this.links.values()].some($=>!$.closed&&!F.has($.pubkey)&&$.have.has(c)&&h($,P)))return this.counters.peerNoFit+=1,this.#N(p,{unfit:[...this.links.values()].filter($=>!$.closed&&!F.has($.pubkey)&&$.have.has(c)&&!h($,P)).map($=>$.pubkey)}),null;await this.#ee(c,Math.min(100,r.deadline-I()),t);continue}F.add(S.pubkey),p.asked.add(S.pubkey),x&&(this.counters.peerUntestedTrial+=1);let M=this.peerSelection.estimate(S,A.size);M!==null&&r.extend(I()+M*1.25+25)&&(this.counters.peerWaitExtended+=1);let H=I(),D=r.deadline-I(),B=[...this.links.values()].filter($=>this.#P($)&&!F.has($.pubkey)&&$.have.has(c)&&h($,D)).length,U=D-Math.min(2,B)*25,C=M===null?Math.min(D,Math.max(25,U)):Math.min(D,Math.max(25,D/Math.min(3,B+1),M*1.25+25)),z=this.#Je(t,H,A.size,r,N),ee;try{ee=await S.request(c,Math.max(1,C),{signal:z.signal,expectedSize:A.size,onProgress:z.progress,onResult:$=>this.#we(e,S,D,$,null,o)})}finally{z.done()}if(this.peerSelection.observe(z.observation()),z.abandoned)return this.#T(S,I()-H),this.counters.peerAbandoned+=1,this.#N(p),null;if(!ee||t.aborted||this.stopped){!t.aborted&&!this.stopped&&this.#T(S,I()-H);continue}let te=await Pt(ee);if(this.stopped)return null;if(ee.byteLength!==A.size||te!==A.sha256){if(this.#T(S,I()-H),this.counters.peerCorrupt+=1,this.banned.add(S.pubkey),p.asked.delete(S.pubkey),S.close("integrity"),t.aborted)return r.expired&&this.#N(p),null;continue}return t.aborted?(r.expired&&this.#N(p),null):A.expiresAt<=Math.floor(Date.now()/1e3)?null:(this.#T(S,I()-H,ee.byteLength),g&&(this.counters.coordinatedPeerLoads+=1),x&&(this.counters.peerUntestedTrialLoaded+=1),{key:c,bytes:ee,discoveryContext:l,holderContext:d,pubkey:S.pubkey,demand:p,connection:S.pc})}return!this.stopped&&(!t.aborted||r.expired)&&this.#N(p),null}#Ye(e){let t=this.transferIds.get(e);return t===void 0&&(t=this.nextTransferId++,this.transferIds.set(e,t)),t}#P(e){return!e.closed&&!e.busy&&!this.peerLeases.has(e)}#K(e,t){return this.#P(e)||!!(t?.[ke]&&!e.closed&&this.peerLeases.has(e))}#Ze(e,t,r){return this.peerAdmission.waited++,new Promise(s=>{let i,o=c=>{this.peerLeaseWaiters.delete(l)&&(clearTimeout(i),this.timers.delete(i),r.removeEventListener("abort",a),this.peerAdmission[c]++,s(c==="granted"))},a=()=>o("cancelled"),l=()=>{if(this.stopped||r.aborted)return a();if(I()>=t)return o("expired");e.some(c=>this.links.get(c.pubkey)===c&&this.#P(c))&&o("granted")};this.peerLeaseWaiters.add(l),r.addEventListener("abort",a,{once:!0}),i=setTimeout(()=>o("expired"),Math.max(0,t-I())),this.timers.add(i),l()})}async#Xe(e,t,r,s,i,o,a){if(r.currentValid&&!r.currentValid())return null;let l=this.options.transferWorkerUrl!==void 0;if(l&&(!this.#A()||this.transferWorkerState!=="ready"))return null;if(!this.#A()||!Array.isArray(i.pieces))return;let c=gl(e.url);if(!r.peerOnly&&this.originsWithoutRanges.has(c))return l?null:void 0;let u=w=>this.links.get(w.pubkey)===w&&!w.closed&&w.supportsRanges===!0&&w.have.has(s)&&!this.banned.has(w.pubkey)&&(this.remoteFraming.get(w.pubkey)??1)>=2&&(!r.cachedHolders||r.cachedHolders.has(w)),d=[...this.links.values()].filter(w=>u(w)&&this.#K(w,e)),p=()=>d.filter(w=>u(w)&&this.#P(w)),g=p();if(!g.length&&e?.[ke]&&d.some(w=>this.peerLeases.has(w))&&(await this.#Ze(d,r.limit,t),g=p()),this.stopped||t.aborted||I()>=r.limit||typeof r.revalidateAuthority=="function"&&!r.revalidateAuthority())return null;if(!g.length)return l?null:void 0;let f=new Map(g.map(w=>[w,this.#$e(w,Math.max(0,r.limit-I()),i.pieceSize)]).filter(([,w])=>w!==null));if(!f.size)return this.counters.peerNoFit+=1,null;let m=[...f.keys()],b={};for(let w of m)this.peerLeases.set(w,b);this.peerAdmission.claims+=m.length;let v=()=>{t.removeEventListener("abort",v);for(let w of m)this.peerLeases.get(w)===b&&this.peerLeases.delete(w);for(let w of[...this.peerLeaseWaiters])this.#h(0,w);this.latePeerOwners.size&&this.#h(0,()=>this.#k())};t.addEventListener("abort",v,{once:!0});try{let w=new Map(m.map(S=>[this.#Ye(S),S])),T=Math.floor(r.limit),O=r.peerOnly?r.limit:r.limit+r.originReserveMs,K={size:i.size,sha256:i.sha256,pieces:i.pieces,deadline:T,maxHolders:this.options.maxHoldersPerObject,originReserveMs:0,...r.peerOnly?{peerOnly:!0}:{}},A;try{A=l?await this.transferWorker.transfer(K,{signal:t}):this.core.transfer(K)}catch{return null}if(this.stopped||t.aborted||l&&I()>=T||r.currentValid&&!r.currentValid()||typeof r.revalidateAuthority=="function"&&!r.revalidateAuthority()||m.some(S=>!u(S)||S.busy||this.peerLeases.get(S)!==b))return A?.free(),null;if(!A)return l||r.peerOnly?null:void 0;this.multiHolder.transfers+=1;let k=a,W=this.traceBase,_=(S,M,H)=>{let D=Math.floor(I()),B=C=>(this.options.traceRequests&&this.#e({k:"xfer",load:k,op:S,at:D-W,...M,out:C&&{c:C.commands.map(({t:z,peer:ee,p:te})=>({t:z,...ee!==void 0?{peer:ee}:{},...te?{p:[...te]}:{}})),next:C.next===null?null:C.next-W,late:C.late,finished:C.finished}}),C),U=H(D);return U?.then?U.then(B):B(U)};r.extend(r.limit);let F=i.pieceSize,P=({start:S,end:M})=>[S*F,Math.min(M*F,i.size)],N=[...w].map(([S,M])=>[S,f.get(M).firstByteMs,f.get(M).rate]),h=r.peerOnly?null:Be(this.#W(e),.5),x=r.peerOnly?null:[0,h?i.size/h:null];return await new Promise(S=>{let M=new Map,H=new Set,D=new WeakSet,B=new Map,U=new Map,C=!1,z=null,ee=null,te=null,$=0,ne=0,ue=this.latePeerGeneration,Z=this.options.streamEvent?.id,oe=this.hls,ge=this.hls?.media,Oe=this.transferWorker,Ke=new Map(m.map(y=>[y,{connection:y.pc,channel:y.channel,flow:new Cr}])),Ee=y=>{Ke.get(y)?.flow.discard(I())},Dt=(y,E,R,q,L)=>{let j=Ke.get(y),Y=I(),Q=q?.firstByteMs,V=q?.elapsedMs,X=V-Q;if(!j)return;if(C||this.stopped||t.aborted||E.signal.aborted||Y>=O||!u(y)||this.peerLeases.get(y)!==b||y.pc!==j.connection||y.channel!==j.channel||this.latePeerGeneration!==ue||this.options.streamEvent?.id!==Z||this.hls!==oe||this.hls?.media!==ge||l&&this.transferWorker!==Oe||q?.outcome!=="payload"||!Number.isFinite(Q)||Q<0||!Number.isFinite(V)||X<0||!Number.isFinite(R)||!Number.isSafeInteger(L)||L<0||!Number.isSafeInteger(q.receivedBytes)||L>q.receivedBytes||X>=Wr){Ee(y);return}if(!L)return;let de=j.flow.record({freshBytes:L,startAt:R+Q,endAt:Y});if(!de)return;this.peerSelection.observe(de);let J=this.#J(y);J.flows.push({value:Math.min(1e6,de.bytes/de.flowMs),flowMs:de.flowMs,at:Y}),J.flows.length>Xn&&J.flows.shift()},se=(y,E)=>{let R=y?.verified==null?0:Math.max(0,y.verified-ne);return y?.verified!=null&&(ne=Math.max(ne,y.verified)),this.multiHolder.unusedBytes+=E-R,R},et=I(),St=0,Et=0,Ut=y=>(y!==null&&(clearTimeout(y),this.timers.delete(y)),null),Re=y=>{if(!C){C=!0,Ke.clear(),z=Ut(z),ee=Ut(ee);for(let E of[...M.values(),...H])E.abort();te?.(),r.onDeadline=null,t.removeEventListener("abort",tt),A.free(),S(y)}},tt=()=>Re(null);t.addEventListener("abort",tt,{once:!0});let Ie=(y,E,R,q=Ve)=>{if(C)return;let L=j=>{if(!C){if(r.currentValid&&!r.currentValid()||(l||r.peerOnly)&&I()>=O)return Re(null);j?q(j):Re(null)}};try{let j=_(y,E,R);j?.then?j.then(L,()=>Re(null)):L(j)}catch{Re(null)}},Gr=(y,E)=>{if(y.t==="request"){let R=w.get(y.peer),q=new AbortController;M.set(y.peer,q);let[L,j]=P(y.range),Y=I(),Q=Math.max(1,T-Y),V=null,X=-1/0;Et+=1,f.get(R).refresh&&(f.get(R).refreshStartedAt??=I(),f.get(R).state.probeAt=I());let de=J=>{let re=I();C||M.get(y.peer)!==q||re-XA.progress(le,y.peer,J)))};R.request(s,Q,{signal:q.signal,expectedSize:j-L,onProgress:de,range:{start:y.range.start,end:y.range.end,objectSize:i.size},onResult:J=>{V=J,J.outcome!=="payload"&&Ee(R),this.#we(e,R,Q,J,y.range,a)}}).then(J=>{M.get(y.peer)===q&&M.delete(y.peer),St=Math.max(St,I()-Y),!C&&(V?.firstByteMs!==null&&V?.elapsedMs!==null&&V?.receivedBytes&&(V.elapsedMs-V.firstByteMs>=Wr&&V.receivedBytes>=Kr&&Ee(R),this.peerSelection.observe({firstByteMs:V.firstByteMs,bytes:V.receivedBytes,flowMs:V.elapsedMs-V.firstByteMs})),J?(this.#T(R,I()-Y,J.byteLength),Ie("delivered",{source:y.peer,p:[y.range.start,y.range.end],bytes:J.byteLength},re=>A.delivered(re,y.peer,y.range,J),re=>{let le=se(re,J.byteLength);re.commands.some(ie=>ie.t==="fail"||["ban","cancel","abandon"].includes(ie.t)&&ie.peer===y.peer)?Ee(R):Dt(R,q,Y,V,le),this.multiHolder.peerBytes+=le,le>0&&B.set(R.pc,(B.get(R.pc)??0)+le);let pe=V?.elapsedMs-V?.firstByteMs;le>0&&f.get(R).refresh&&V?.receivedBytes>=Kr&&Number.isFinite(pe)&&pe>=0&&peA.failed(re,y.peer))))},()=>{Ee(R),C||Ie("failed",{source:y.peer},J=>A.failed(J,y.peer))})}else if(y.t==="origin"){if(r.peerOnly){this.multiHolder.failed+=1,Re(null);return}te??=this.#Z(s);let R=new AbortController,[q,L]=P(y.range),j=I(),Y=null,Q=X=>{Y=X,this.originRangeOutcomes[X.outcome]=We(this.originRangeOutcomes[X.outcome])};H.add(R),this.multiHolder.originRanges+=1;let V=()=>{this.originsWithoutRanges.has(c)||(this.originsWithoutRanges.add(c),this.multiHolder.originRangesIgnored+=1)};(r.origin?.Loader?Vi(r.origin,e,q,L,{signal:R.signal,onIgnored:V,onResult:Q}):$i(e,q,L,{signal:R.signal,onIgnored:V,onResult:Q})).then(X=>{if(H.delete(R),this.options.traceRequests&&this.#e({k:"origin",load:k,at:this.#s(j),ms:Math.round(I()-j),ranged:!0,range:[y.range.start,y.range.end],outcome:Y?.outcome??(X?"payload":C?"abort":"none"),httpStatus:Y?.httpStatus??null,bytes:X?.byteLength??null}),C)return;let de=[y.range.start,y.range.end];if(!X)return Ie("failed",{source:"origin"},J=>A.failed(J,"origin"));this.#Ke(e,I()-j,X.byteLength,i.size),this.counters.bytesFromOrigin+=X.byteLength,Ie("delivered",{source:"origin",p:de,bytes:X.byteLength},J=>A.delivered(J,"origin",y.range,X),J=>{let re=se(J,X.byteLength);this.multiHolder.originBytes+=re,$+=re,Ve(J)})})}else if(y.t==="cancel"||y.t==="abandon"){Ee(w.get(y.peer));let R=M.get(y.peer);y.t==="abandon"&&(this.multiHolder.abandoned+=1,R&&D.add(R)),R?.abort(y.t==="abandon"?at.ABANDON_REASON:void 0)}else if(y.t==="ban"){let R=w.get(y.peer);Ee(R),this.multiHolder.bans+=1,this.counters.peerCorrupt+=1,this.banned.add(R.pubkey),R.close("integrity")}else if(y.t==="deliver"){this.multiHolder.delivered+=1,this.multiHolderTimings.push([I()-et,St,Et]),this.multiHolderTimings.length>128&&this.multiHolderTimings.shift();let R=E.bytes.byteOffset===0&&E.bytes.byteLength===E.bytes.buffer.byteLength?E.bytes:E.bytes.slice();Re(i.expiresAt<=Math.floor(Date.now()/1e3)?null:{key:s,bytes:R,discoveryContext:o,multi:!0,peerBytes:Math.max(0,i.size-$),contributions:[...B].map(([q,L])=>({connection:q,bytes:L})),shortRefreshes:[...U].map(([q,L])=>({connection:q,at:L}))})}else y.t==="fail"&&(this.multiHolder.failed+=1,Re(null))},Ve=y=>{if(!C){if(!y)return Re(null);for(let E of y.commands)if(Gr(E,y),C)return;z=Ut(z),y.next!==null&&(z=this.#h(Math.max(0,y.next-I()),()=>{z=null,Ie("tick",{},E=>A.tick(E))}))}};r.onDeadline=()=>C?!1:(Ie("tick",{},y=>A.tick(y)),!C&&ee===null&&(ee=this.#h(Math.max(0,r.limit+r.originReserveMs-I()),()=>{ee=null,Re(null)})),!0);let Yr=[...f.values()].some(y=>y.refresh||y.firstByteMs===null)?null:this.peerSelection.firstByteMs(),ir=[...w].filter(([,y])=>f.get(y).rate===null).map(([y])=>y),Zr={peers:N,origin:x,sharedFirstByteMs:Yr,sharedRate:this.peerSelection.rate(),probePeers:ir};Ie("start",this.options.traceRequests?{size:i.size,pieces:i.pieces.length,pieceSize:F,deadline:T-W,maxHolders:this.options.maxHoldersPerObject,originReserveMs:0,...r.peerOnly?{peerOnly:!0}:{},...structuredClone(Zr),holders:[...w].map(([y,E])=>[y,this.#U(E.pubkey)])}:null,y=>A.start(y,Zr),y=>{y?.late&&(this.multiHolder.late+=1),Ve(y)})})}finally{v()}}#Je(e,t,r,s,i){let o=new AbortController,a=()=>o.abort(e.reason);e.aborted?a():e.addEventListener("abort",a,{once:!0});let l=[],c=this.peerSelection.rate(),u=null,d={abandoned:!1,signal:o.signal},p=()=>{d.abandoned||o.signal.aborted||(d.abandoned=!0,o.abort(at.ABANDON_REASON))},g=null;if(i!==null){let m=c?s.deadline-r/c:-1/0;g=setTimeout(()=>{u===null&&p()},Math.max(bl,i*3,m-I()))}let f=m=>{let b=l.at(-1);if(!b)return null;let v=l[0];for(let w of l)if(w[0]<=b[0]-m)v=w;else break;return b[0]-v[0]>=150?{bytes:b[1]-v[1],ms:b[0]-v[0]}:null};return d.progress=(m,b,v)=>{let w=I();if(u===null&&(u=Number.isFinite(v)?v:w-t),l.push([w,m]),l.length>256&&l.shift(),w-ts.deadline)&&p()},d.observation=()=>{let m=l.length?l.at(-1)[0]-l[0][0]:0,b=f(Math.max(300,m/2));return{firstByteMs:u,bytes:b?.bytes??0,flowMs:b?.ms??0,totalFlowMs:m}},d.done=()=>{clearTimeout(g),e.removeEventListener("abort",a)},d}#T(e,t,r){this.peerSelection.record(e,t,r),e.closed&&this.peerSelection.forget(e)}#we(e,t,r,s,i=null,o=null){try{if(!no.includes(s.outcome))return;this.#Ve(t,s);let a=p=>Number.isFinite(p)&&p>=0?p:null,l=p=>Number.isSafeInteger(p)&&p>=0?p:null,c=null,u=null;try{c=l(e?.frag?.cc)}catch{}try{u=l(e?.frag?.level)}catch{}let d={atMs:Math.max(0,Math.round(I()-this.transportStartedAt)),id:this.transportConnections.get(t.pc)?.id||0,holder:this.#U(t.pubkey),cc:c,level:u,remainingMs:a(r),outcome:s.outcome,elapsedMs:a(s.elapsedMs),timeoutMs:a(s.timeoutMs),expectedBytes:l(s.expectedBytes),receivedBytes:l(s.receivedBytes),firstByteMs:a(s.firstByteMs),metadataReceived:s.metadataReceived===!0,draining:s.draining===!0,closeReason:$r["link-close"].includes(s.closeReason)?s.closeReason:null};this.peerRequestCounters[s.outcome]=We(this.peerRequestCounters[s.outcome]),this.peerRequestRecords.length===64&&(this.peerRequestRecords.shift(),this.peerRequestDropped=We(this.peerRequestDropped)),this.peerRequestRecords.push(d),this.#e({k:"request",load:o,at:this.#s(),range:i?[i.start,i.end]:null,...d})}catch{}}#Qe(e){let t=this;class r{static relayswarmShadow=!0;constructor(i){this.inner=new e(i)}get stats(){return this.inner.stats}get context(){return this.inner.context}load(i,o,a){t.#Y(i);let l=t.#et(i);if(this.race=l,!l)return this.inner.load(i,o,a);let c=[],u=0,d=l.sampled||t.#xe(),p={...a,onProgress:a.onProgress?(g,f,m,b)=>{try{m?.byteLength&&(d&&c.push(m.slice(0)),u+=m.byteLength)}catch{}a.onProgress(g,f,m,b)}:void 0,onSuccess:(g,f,m,b)=>{let v=Vr(f),w=null,T=0;try{let O=g?.data;O?.byteLength?(d&&(w=O.slice(0)),T=O.byteLength):u&&(d&&(w=r.join(c)),T=u)}catch{w=null,T=0}l.originSucceeded=!0,a.onSuccess(g,f,m,b),t.#B(b,v),T?t.#n("origin-loaded",()=>t.#rt(l,w,T)):t.#n("origin-empty",()=>t.#z(l))},onError:(...g)=>{t.#n("origin-error",()=>t.#z(l)),a.onError(...g)},onTimeout:(...g)=>{t.#n("origin-timeout",()=>t.#z(l)),a.onTimeout(...g)}};return a.onAbort&&(p.onAbort=(...g)=>{t.#n("origin-abort",()=>t.#z(l)),a.onAbort(...g)}),this.inner.load(i,o,p)}abort(){return this.race&&t.#z(this.race),this.inner.abort()}destroy(){return this.race&&!this.race.originSucceeded&&!this.race.originDone&&t.#z(this.race),this.inner.destroy()}getCacheAge(){return this.inner.getCacheAge?.()??null}getResponseHeader(i){return this.inner.getResponseHeader?.(i)??null}static join(i){let o=i.reduce((c,u)=>c+u.byteLength,0),a=new Uint8Array(o),l=0;for(let c of i)a.set(new Uint8Array(c),l),l+=c.byteLength;return a.buffer}}return r}#et(e){try{if(this.stopped||this.races.size>=this.options.maxConcurrentRaces)return null;let t=e?.frag;if(!t||t.sn==="initSegment"||e.part&&!this.options.swarmParts)return this.counters.skipped+=1,null;let r=e.url||t.url,s=(this.options.segmentKey||to)(r,e);if(typeof s!="string"||!s)return this.counters.skipped+=1,null;let i=e.rangeEnd?`#${e.rangeStart||0}-${e.rangeEnd}`:"",o={controller:new AbortController,t0:I(),keyText:`${this.options.swarmId} -${s}${i}`,key:null,sampled:Math.random()this.#tt(o)),o}catch(t){return this.#o("begin-race",t),null}}async#tt(e){if(e.keyPromise=Pt(eo.encode(e.keyText)),e.key=await e.keyPromise,this.stopped)return;if(!e.sampled||!this.options.serveOnCellular&&Ht())return e.peerDone=!0,e.skipPeers=!0,this.#n("settle",()=>this.#te(e));let t=e.t0+this.options.lateWindowMs,r=new Set,s=e.peersAtStart>0;for(;!this.stopped&&!e.settled&&!e.originFailed&&I()0,this.#n("settle",()=>this.#te(e))}#ee(e,t,r){return new Promise(s=>{let i=null,o=l=>{l&&!l.includes(e)||(clearTimeout(i),r?.removeEventListener("abort",a),this.haveWaiters.delete(o),s())},a=()=>o();if(r?.aborted)return s();r?.addEventListener("abort",a,{once:!0}),i=setTimeout(o,Math.max(0,Math.min(t,1e3))),this.haveWaiters.add(o)})}async#rt(e,t,r){if(this.stopped||e.originFailed)return;let s=t&&new Uint8Array(t),i=I();this.counters.originLoaded+=1,this.counters.bytesFromOrigin+=r,e.originBytes=r,je(this.originLatencySamples,i-e.t0),e.sampled&&(e.originDigest=await Pt(s)),e.originDone=!0,await e.keyPromise,!this.stopped&&(s&&this.#L(e.key,s),this.#n("settle",()=>this.#te(e)))}#z(e){e.settled||e.originDone||(e.controller.abort(),e.originDone=!0,e.originFailed=!0,this.#n("settle",()=>this.#te(e)))}async#te(e){if(e.settled||!e.originDone||!e.peerDone)return;e.settled=!0,this.races.delete(e);let t=this.counters;if(e.skipPeers)return void(t.sampledOut+=1);if(e.originFailed){e.peerBytes?t.peerUnverified+=1:t.aborted+=1;return}if(t.sampledOriginBytes+=e.originBytes||0,!e.peerBytes){e.sawPeer?(t.raced+=1,t.peerMiss+=1):t.noPeers+=1;return}if(t.raced+=1,await Pt(e.peerBytes)!==e.originDigest){this.#T(e.peerLink,e.requestMs),t.peerCorrupt+=1,this.banned.add(e.peerLink.pubkey),e.peerLink.close("integrity");return}let s=e.peerAt-e.t0;this.#T(e.peerLink,e.requestMs,e.peerBytes.byteLength),this.firstPeerSegmentAtMs===null&&(this.firstPeerSegmentAtMs=Date.now()-this.startedAt),je(this.peerLatencySamples,s),t.bytesFromPeers+=e.peerBytes.byteLength,s<=this.options.originFallbackMs?(t.peerInTime+=1,t.peerInTimeBytes+=e.peerBytes.byteLength):t.peerLate+=1}#L(e,t){if(!this.#p()||this.held.has(e)||t.byteLength>this.options.maxSegmentBytes)return;this.held.set(e,t),this.heldBytes+=t.byteLength;let r=this.#ve(this.options.maxHeldBytes-(this.warmAhead?.snapshot().reservationBytes??0),!1);if(this.#p())for(let s of this.links.values())s.sendHaveChange(this.held.has(e)?[e]:[],r)}#nt(e){let t=this.held.get(e);if(t){this.held.delete(e),this.heldBytes-=t.byteLength,this.warmAhead?.release(e);for(let r of this.links.values())r.sendHaveChange([],[e])}}#ve(e,t=!0){let r=[];for(;this.held.size&&(this.held.size>this.options.maxHeldSegments||this.heldBytes>Math.max(0,e));){let s=this.warmAhead?[...this.held].find(([a])=>!this.warmAhead.pinned(a)):this.held.entries().next().value;if(!s)break;let[i,o]=s;this.held.delete(i),this.heldBytes-=o.byteLength,this.warmAhead?.release(i),r.push(i)}if(t&&r.length)for(let s of this.links.values())s.sendHaveChange([],r);return r}#xe(){return!this.stopped&&!this.disabledReason&&this.options.serve===!0}#p(){return!this.stopped&&!this.disabledReason&&this.options.serve===!0&&this.#H()!==0&&(this.options.serveOnCellular||!Ht())}#H(){let e=this.options.maxUploadBytesPerSession;return!Number.isSafeInteger(e)||e<0?null:Math.max(0,e-this.uploadQuotaBytes)}#Se(){this.warmAhead?.clear();for(let e of this.cachedRaces)e.abort();this.held.clear(),this.heldBytes=0,this.uploadPacer?.recheck();for(let e of this.links.values())e.sendHave([]),e.sendContribution(!1,this.rendition);this.#V()}async#st(e,t,r=null){if(this.uploadPacer)return this.#it(e,t,r);let s=this.admissionChecks.get(e.pubkey)?.ticket??this.admitted.get(e.pubkey)?.ticket;if(this.options.admit&&!await this.#x(e.pubkey,s,"upload"))return this.#y("admission"),e.close("admission"),null;if(e.closed)return null;let i=this.held.get(t);if(!i)return this.#y("not-held"),null;let o=i.byteLength;if(r){let u=xt(i.byteLength),d=r.start*u,p=Math.min(r.end*u,i.byteLength);if(!(da)return this.#y("session-allowance"),null;let l=[...this.links.values()].filter(u=>u!==e&&(u.outboundInFlight>0||Date.now()-u.lastServedAt<3e4)).length;if(Date.now()-e.lastServedAt>=3e4&&l>=this.options.maxUploadPeers)return this.#y("peer-limit"),null;let c=(I()-this.uploadRefilledAt)/1e3;if(this.uploadRefilledAt=I(),this.uploadTokens=Math.min(this.options.maxUploadBytesPerSecond*2,this.uploadTokens+c*this.options.maxUploadBytesPerSecond),this.uploadTokensthis.options.reserveUploadBytes(o,{signal:d}),this.lifecycle.signal,this.options.admissionTimeoutMs)===!0}catch{this.#o("upload-reservation")}if(!u||this.stopped||e.closed||this.options.serve!==!0||!this.options.serveOnCellular&&Ht())return u||(this.uploadQuotaBytes-=o),this.#y(u?"reservation-inactive":"reservation-refused"),null}if(this.counters.bytesUploaded+=o,this.counters.uploadsServed+=1,this.options.testHooks?.corruptUploads){let u=i.slice();return u[u.length>>1]^=255,u}return i}#y(e){this.counters.uploadsRefused+=1,this.uploadRefusalCounters[e]=We(this.uploadRefusalCounters[e])}#Ee(){let e=I(),t=Math.max(0,e-this.uploadRefilledAt)/1e3;this.uploadRefilledAt=e,this.uploadTokens=Math.min(this.options.maxUploadBytesPerSecond*2,this.uploadTokens+t*this.options.maxUploadBytesPerSecond)}#Ae(e,t){let r=this.held.get(e)?.byteLength;if(!Number.isSafeInteger(r)||r<1)return null;if(!t)return{key:e,size:r,charge:r,range:null};let s=xt(r);if(!Number.isSafeInteger(t.start)||!Number.isSafeInteger(t.end)||t.start<0||t.end<=t.start||t.end>Math.ceil(r/s))return null;let i=Math.min(t.end*s,r)-t.start*s;return{key:e,size:r,charge:i,range:{start:t.start,end:t.end}}}#ke(e,t=!1){if(this.stopped||this.disabledReason||!this.options.serve||e.link.closed||this.links.get(e.link.pubkey)!==e.link||!this.options.serveOnCellular&&Ht()||this.banned.has(e.link.pubkey))return!1;let r=this.#Ae(e.key,e.range);if(!r||r.size!==e.size||r.charge!==e.charge)return!1;let s=this.#H();if(!t&&s!==null&&e.charge>s)return!1;let i=[...this.links.values()].filter(o=>o!==e.link&&(o.outboundInFlight>0||Date.now()-o.lastServedAt<3e4)).length;return Date.now()-e.link.lastServedAt<3e4||ii.active&&!c.aborted&&this.#ke(i,o);try{if(!u())return null;let d=this.admissionChecks.get(e.pubkey)?.ticket??this.admitted.get(e.pubkey)?.ticket;if(this.options.admit&&!await lt(()=>this.#x(e.pubkey,d,"upload"),c,this.options.admissionTimeoutMs))return this.#y("admission"),e.close("admission"),null;if(!u())return null;if(this.uploadQuotaBytes+=i.charge,o=!0,this.options.reserveUploadBytes){try{a=await lt(g=>this.options.reserveUploadBytes(i.charge,{signal:g}),c,this.options.admissionTimeoutMs)===!0}catch{this.#o("upload-reservation")}if(a!==!0)return this.#y("reservation-refused"),null}else a=!0;if(!u()||this.options.admit&&this.admitted.get(e.pubkey)?.ticket!==d)return this.#y("reservation-inactive"),null;let p=this.held.get(t);if(!p||p.byteLength!==i.size)return this.#y("not-held"),null;if(this.counters.bytesUploaded+=i.charge,this.counters.uploadsServed++,l=!0,this.options.testHooks?.corruptUploads){let g=p.slice();return g[g.length>>1]^=255,g}return p}catch{return null}finally{o&&a===!1&&(this.uploadQuotaBytes-=i.charge),o&&this.#H()===0&&this.#Se(),this.uploadPacer.finish(i,l)}}async#ot(){this.coreState="loading";try{let e=await qi(this.options.coreWasm,{onFailure:r=>this.#le(r)});if(this.stopped)return;this.core=e,this.coreVerifier=e.verifier,this.peerSelection.order===0&&(this.peerSelection=e.peerSelection());let t=this.discovery;t.contexts.size===0&&t.candidates.size===0&&!t.window&&(this.discovery=e.neighbourDiscovery(),Object.assign(this.discovery.counters,t.counters)),this.coreState="ready",this.options.transferWorkerUrl!==void 0&&this.#at(e)}catch(e){this.coreState="failed",this.options.transferWorkerUrl!==void 0&&(this.transferWorkerState="failed",this.transferWorkerReason="core-failed"),this.#o("core",e)}}async#at(e){this.transferWorkerState="loading";try{let t=this.options.WorkerImpl,r=await Wi({module:e.module,workerUrl:this.options.transferWorkerUrl,workerFactory:t?(s,i)=>new t(s,i):void 0,signal:this.lifecycle.signal,maxSegmentBytes:Math.min(32*1024*1024,this.options.maxSegmentBytes),onFailure:s=>this.#Me(s)});if(this.stopped||this.core!==e||e.retired){r.stop();return}this.transferWorker=r,this.transferWorkerState="ready"}catch(t){this.stopped||this.#Me(t)}}#Me(e){this.stopped||this.transferWorkerState==="failed"||(this.transferWorkerState="failed",this.transferWorkerReason=typeof e?.code=="string"?e.code:"worker-failed",this.#o("transfer-worker",e))}#le(e){let t=this.#A();this.core?.retire(),this.transferWorker?.stop(),this.options.transferWorkerUrl!==void 0&&(this.transferWorkerState="failed",this.transferWorkerReason="core-failed"),this.coreVerifier=null,this.coreState="failed",this.coreFallbacks+=1,this.#o("core",e),t&&this.#V()}#A(){return this.options.multiHolder===!0&&this.options.mode==="peer-first"&&!!this.core&&!this.core.retired&&this.coreLinks.js===0}#lt(e){if(this.core&&!this.core.retired)try{let t=this.core.peerLink(e);return this.coreLinks.wasm+=1,t}catch(t){this.#le(t)}return this.coreLinks.js+=1,new at(e)}#ce(e,t){if(this.coreVerifier)try{let r=this.coreVerifier.verifySegmentCommitment(e,t);return this.coreDecided.wasm+=1,r}catch(r){this.#le(r)}return this.coreDecided.js+=1,Ii(e,t)}async#ct(){let e=this.options.secretKey||Yt();if(this.pool=new Or(this.options.relays,{label:"hls-swarm",WebSocketImpl:this.options.WebSocketImpl||globalThis.WebSocket,reconnect:!0}),await Promise.all([this.pool.connect(),this.coreWait]),this.stopped)return this.pool.close();this.session=new Ir({pool:this.pool,swarmId:this.options.swarmId,secretKey:e,maxEventAgeSeconds:60}),this.session.onPresence(t=>this.#n("presence",()=>this.#mt(t))),this.session.onSignal(t=>this.#n("signal",()=>this.#yt(t))),this.session.onError(t=>this.#o("session",t)),this.session.start(),this.#V(),this.#M(this.options.presenceIntervalMs,.3,()=>this.#V())}#V(){if(!(!this.session||this.stopped))try{this.session.announcePresence({role:"viewer",transports:[{type:jr,publicKey:this.session.pubkey,...this.#A()?{obj:2}:{}}],have:this.#p()?[...this.held.keys()].slice(-8):[],open:this.#ut(),...this.#se()?{ticket:this.#se()}:{}}),this.counters.presenceSent+=1;for(let[e,t]of this.renditions){if(t{this.reannounceTimer=null,this.#V()})}#F(e,t){return!e.closed&&e.contribution?.serving&&(e.renditions.get(t)||0)>Date.now()-3e4}#he(e){return![...this.links.values()].some(t=>!this.discovery.stale(e,t.pubkey)&&(this.#F(t,e.rendition)||e.keys.some(r=>t.have.has(r))))}#Re(e){let t=[...this.links.values()].filter(r=>this.#F(r,e.rendition));return t.length>0&&t.every(r=>this.discovery.stale(e,r.pubkey))}#ht(e){return[...this.links.values()].filter(t=>this.#F(t,e.rendition)).every(t=>this.discovery.stale(e,t.pubkey))}#Te(e){return!this.links.has(e.pubkey)&&!this.dials.has(e.pubkey)&&!this.dialChecks.has(e.pubkey)&&!this.#D(e.pubkey)&&(!this.#G()||ye(e.ticket))&&(this.retries.get(e.pubkey)||0)<=this.options.maxRetriesPerPeer}#Le(e){if(this.discovery.spent(e)||this.links.size<2||Date.now()-this.lastEvictionAtDate.now()-r.activityAt<3e4);return oo([...this.links.values()].filter(r=>!t.some(s=>!this.discovery.stale(s,r.pubkey)&&(this.#F(r,s.rendition)||s.keys.some(i=>r.have.has(i))))),{...this.options,banned:this.banned,tier:r=>this.#Ie(r)})}#q(e=this.discovery.window,t=!0){if(!e||!this.discovery.end(e))return;clearTimeout(e.timer),this.timers.delete(e.timer);let r=e.attempt,s=r?.dial;t&&s&&s.discovery===r&&s.negotiation===r.negotiation&&this.dials.get(s.pubkey)===s&&(s.discovery=null,this.#m(s,"superseded"))}#j(e=!0){let t=this.discovery.window;t&&(!this.discovery.live(t)||!this.discovery.current(t.context)||e&&t.attempt&&!this.discovery.valid(t.attempt))&&(this.discovery.counters.expired++,this.#q(t))}#re(){if(this.stopped||this.options.mode!=="peer-first"||(this.#j(),!this.#ne()))return;for(let i of this.discovery.contexts.values())this.discovery.rearm(i,()=>this.#ht(i));let e=this.links.size+this.dials.sizethis.#Te(i),i=>this.#he(i)&&(e||this.discovery.reserved()||!!this.#Le(i)),e);if(!t)return;let r=this.discovery.begin(t);if(!r)return;this.#Re(t.context)&&this.discovery.counters.staleHolder++;let s=r.window;s.timer||(s.timer=this.#h(Math.max(0,s.expiresAt-Date.now()),()=>this.#q(s))),this.#n("discovery",()=>this.#oe(r.pubkey,r))}#$(e,t){this.openPeers.set(e,{open:t,at:Date.now()}),this.openPeers.size>64&&this.openPeers.delete(this.openPeers.keys().next().value)}#_e(){let e=Date.now()-6e4;return[...this.openPeers.entries()].filter(([t,r])=>r.open&&r.at>=e&&!this.banned.has(t)).sort((t,r)=>r[1].at-t[1].at).map(([t])=>t)}#Oe(){return oo(this.links.values(),{...this.options,banned:this.banned,tier:e=>this.#Ie(e)})}#Ie(e){if(e.contribution?.serving===!0)return 1;if(!this.#p())return 0;let t=Date.now(),r=2*this.options.presenceIntervalMs;for(let[s,i]of e.announced??[]){if(t-i>r)continue;let o=this.renditions.get(s);if(o!==void 0&&t-o<=3e4)return 2}return 0}#Ce(e,t,r){let s=["Unhelpful","Serving","Consumer"][t];e[`${r}${s}`]++}#ut(){return this.#j(),this.discovery.reserved()?!1:this.#_()||this.links.size>=2&&!!this.#Oe()}#dt(e,t){if(this.discovery.reserved())return null;let r=Number.isSafeInteger(e)&&e>0&&typeof t=="string"&&/^[0-9a-f]{64}$/u.test(t)&&this.held.has(t)&&this.#p();if(e!==0&&!r||this.links.size<2||Date.now()-this.lastEvictionAts!==e).slice(0,this.options.maxReferrals);return r.length&&(this.counters.referralsSent+=r.length),{retryAfterMs:t,referrals:r}}#ue(e,t,r,s={}){try{return this.stopped?!1:(this.session.sendSignal(e,{type:t,transport:jr,requestId:r,payload:s}),this.counters.signalsSent+=1,!0)}catch(i){return this.counters.publishErrors+=1,this.#o("signal-send",i),!1}}#pt(e){return Al(e,this.options)}#gt(e,{retryAfterMs:t,referrals:r}){let s=(this.retries.get(e)||0)+1;s<=this.options.maxRetriesPerPeer&&(this.retries.set(e,s),this.counters.retriesScheduled+=1,this.#h(t+Math.random()*1e3,()=>{if(this.discovery.reserved()){this.cooldowns.delete(e),this.#re();return}if(!(this.links.has(e)||this.dials.has(e)||this.banned.has(e)||!this.#_()))return this.cooldowns.delete(e),this.#oe(e)}));for(let i of r)if(i!==this.session?.pubkey&&!(this.#G()&&!this.admitted.has(i))&&!(this.links.has(i)||this.dials.has(i)||this.#D(i)||!this.#_())){if([...this.dials.values()].filter(o=>o.outgoing).length>=this.options.maxDialsInFlight)break;this.counters.referralsFollowed+=1,this.#n("referral",()=>this.#oe(i))}}#_(){return this.#j(),this.links.size+this.dials.size+(this.discovery.reserved()?1:0)e.outgoing).length+this.dialChecks.sizeDate.now()}#G(){return typeof this.options.admit=="function"}#se(){return ye(this.options.ticket)?this.options.ticket:void 0}async#x(e,t,r="other"){if(this.stopped)return!1;if(!this.#G())return!0;if(!ye(t))return this.counters.admitRefused+=1,!1;let s=this.admissionChecks.get(e);if(s)return s.ticket===t?s.promise:!1;if(this.admissionChecks.size>=16)return!1;let i={ticket:t,promise:null};return i.promise=(async()=>{let o=!1;try{o=await lt(a=>{try{let l=so.includes(r)?r:"other";this.admissionCallCounters[l]=We(this.admissionCallCounters[l])}catch{}return this.options.admit(e,t,{signal:a})},this.lifecycle.signal,this.options.admissionTimeoutMs)===!0}catch(a){this.#o("admit",a)}if(this.stopped||this.admissionChecks.get(e)!==i)return!1;if(o){let a=this.admitted.get(e)?.candidateTicket;this.admitted.set(e,{ticket:t,...ye(a)&&a!==t?{candidateTicket:a}:{}}),this.admitted.size>256&&this.admitted.delete(this.admitted.keys().next().value)}else{let a=this.admitted.get(e);a?.ticket===t?this.admitted.delete(e):a?.candidateTicket===t&&delete a.candidateTicket,this.counters.admitRefused+=1}return o})().finally(()=>{if(this.admissionChecks.get(e)!==i)return;this.admissionChecks.delete(e);let o=i.latestPresence;o&&!this.stopped&&(this.links.has(e)||this.dials.has(e))&&this.#n("admission-refresh",async()=>{await this.#x(e,o.ticket,"refresh")&&o.open!==null&&this.#$(e,o.open)})}),this.admissionChecks.set(e,i),i.promise}#Ne(e,t){t===2&&(this.remoteFraming.delete(e),this.remoteFraming.set(e,2),this.remoteFraming.size>1024&&this.remoteFraming.delete(this.remoteFraming.keys().next().value))}async#mt({from:e,payload:t}){if(this.stopped||t.role!=="viewer")return;let r=t.transports.find(l=>l.type===jr);if(!r)return;this.remoteFraming.delete(e),this.remoteFraming.set(e,r.obj??1),this.remoteFraming.size>1024&&this.remoteFraming.delete(this.remoteFraming.keys().next().value),this.options.mode==="peer-first"&&(this.discovery.hint(e,t.have,t.ticket),this.#re());let s=this.links.has(e)||this.dials.has(e),i=this.admitted.get(e);i&&ye(t.ticket)&&t.ticket!==i.ticket&&(i.candidateTicket=t.ticket);let o=!this.#G()||i&&i.ticket===t.ticket;if(s&&o){t.open!==null&&this.#$(e,t.open),this.#k();return}if(!s&&(this.#D(e)||!this.#_()||!this.#ne())){o&&t.open!==null&&this.#$(e,t.open);return}let a=this.admissionChecks.get(e);if(s&&a){ye(t.ticket)&&t.ticket!==a.ticket&&(a.latestPresence={ticket:t.ticket,open:t.open});return}!await this.#x(e,t.ticket,"presence")||this.stopped||(t.open!==null&&this.#$(e,t.open),this.#k(),!(this.links.has(e)||this.dials.has(e)||this.#D(e)||!this.#_())&&this.#h(Math.random()*1500,()=>{if(!(this.links.has(e)||this.dials.has(e)||this.#D(e)||!this.#_())&&this.#ne())return this.#oe(e)}))}#g(e,t,r,s){try{if(!$r[t]?.includes(r))return;let i=this.transportConnections.get(e);if(i?.ended)return;let o=I()-this.transportStartedAt,a={id:i?.id??0,atMs:Number.isFinite(o)?Math.max(0,Math.round(o)):0,event:t,detail:r};Number.isSafeInteger(s)&&s>=0&&s<=256&&(a.candidates=s,a.candidatesCapped=s===256),this.transportCounters[t][r]=We(this.transportCounters[t][r]),this.transportRecords.length===64&&(this.transportRecords.shift(),this.transportDropped=We(this.transportDropped)),this.transportRecords.push(a)}catch{}}#Pe(e,t,r){try{let s,i=e.localDescription?.sdp;if(typeof i=="string"&&i.length<=256*1024){s=0;for(let o of i.matchAll(/^a=candidate:/gm))if(++s===256)break}this.#g(e,`local-${t}`,r,s)}catch{this.#g(e,`local-${t}`,r)}}#de(e,t,r){this.#g(e,t,r);let s=this.transportConnections.get(e);if(!(!s||s.ended)){s.ended=!0;for(let[i,o]of s.listeners)try{e.removeEventListener?.(i,o)}catch{}s.listeners.length=0}}#He(e){let t=this.options.RTCPeerConnectionImpl||globalThis.RTCPeerConnection,r=new t({iceServers:this.options.iceServers,iceTransportPolicy:this.options.iceTransportPolicy}),s={id:this.transportSequence{try{let c=r[o];this.#g(r,i,$r[i].includes(c)?c:"unknown")}catch{this.#g(r,i,"unknown")}};try{r.addEventListener(a,l),s.listeners.push([a,l]),l()}catch{}}return r}#u(e,t){return!this.stopped&&this.dials.get(e.pubkey)===e&&e.negotiation===t&&!t.controller.signal.aborted&&(!e.discovery||this.discovery.valid(e.discovery))}#ie(e,t=!0){let r=e.negotiation;if(r&&(r.controller.abort(),r.onDataChannel&&e.pc.removeEventListener("datachannel",r.onDataChannel),r.channel&&r.onOpen&&r.channel.removeEventListener("open",r.onOpen),t))try{r.channel?.close()}catch{}}#De(e,t,r){!r&&e.discovery&&(this.#q(e.discovery.window,!1),e.discovery=null),e.negotiation&&(e.negotiation.superseded=!0),this.#ie(e),e.requestId=t,e.outgoing=r;let s={controller:new AbortController,channel:null,ready:!1};return e.negotiation=s,s}#fe(e,t,r){let s=(e.operations??Promise.resolve()).then(()=>{if(this.#u(e,t))return r()});return e.operations=s.catch(()=>{}),s}#Ue(e,t,r){if(t.channel!==r){if(!this.#u(e,t)||t.channel){try{r.close()}catch{}return}t.channel=r,t.onOpen=()=>{t.ready&&this.#n("link-open",()=>this.#bt(e,t,r))},r.addEventListener("open",t.onOpen),r.readyState==="open"&&t.onOpen()}}#ze(e,t){this.#u(e,t)&&(t.ready=!0,t.channel?.readyState==="open"&&t.onOpen())}async#oe(e,t=null){if(this.stopped||this.links.has(e)||this.dials.has(e)||this.dialChecks.has(e)||this.#D(e)||!(t?this.discovery.valid(t):this.#_())||!this.#ne()){t&&this.discovery.abandoned(t);return}this.dialChecks.add(e);try{if(!await this.#x(e,t?t.ticket:this.admitted.get(e)?.candidateTicket??this.admitted.get(e)?.ticket,"dialStart")){t&&(this.discovery.abandoned(t),this.cooldowns.set(e,Date.now()+6e4));return}}finally{this.dialChecks.delete(e)}if(this.stopped||this.links.has(e)||this.dials.has(e)||this.#D(e)||[...this.dials.values()].filter(a=>a.outgoing).length>=this.options.maxDialsInFlight||(t?!this.discovery.valid(t)||!this.#he(t.window.context):!this.#_())){t&&this.discovery.abandoned(t);return}if(t&&this.links.size+this.dials.size>=this.options.maxPeers){let a=this.#Le(t.window.context),l=a?.link;if(!l||!this.discovery.replaced(t,l.pubkey)){this.discovery.abandoned(t);return}this.lastEvictionAt=Date.now(),this.counters.evicted++,this.#Ce(this.discovery.counters,a.tier,"victim"),this.cooldowns.set(l.pubkey,t.window.expiresAt),l.close("rotation")}let r=this.#He(!0),s=Sl(),i={pubkey:e,pc:r,startedAt:I(),offerSentAt:0};t&&(i.discovery=t,this.discovery.allocated(t,i)),this.dials.set(e,i);let o=this.#De(i,s,!0);t&&(t.negotiation=o),this.counters.dialsStarted+=1,i.timer=this.#h(t?Math.min(this.options.dialTimeoutMs,Math.max(0,t.window.expiresAt-Date.now())):this.options.dialTimeoutMs,()=>this.#m(i,"timeout"));try{this.#Ue(i,o,r.createDataChannel("relayswarm",{ordered:!0})),await this.#fe(i,o,async()=>{let a=await r.createOffer();if(!this.#u(i,o)||(await r.setLocalDescription(a),!this.#u(i,o))||(await io(r,1200,o.controller.signal,u=>{i.negotiation===o&&!o.superseded&&this.#Pe(r,"offer",u)}),!this.#u(i,o)))return;if(!await this.#x(e,this.admitted.get(e)?.candidateTicket??this.admitted.get(e)?.ticket,"offerBeforeSend")){this.#u(i,o)&&this.#m(i,"failed",0,"admission");return}if(!this.#u(i,o))return;i.offerSentAt=I();let l=this.#se(),c=this.#ue(e,"offer",s,{sdp:r.localDescription.sdp,peers:this.links.size,...this.#A()?{obj:2}:{},...i.discovery?{requestedKey:i.discovery.key}:{},...l?{ticket:l}:{}});this.#g(r,c?"signal-send":"signal-failed","offer"),c||this.#m(i,"failed")})}catch(a){if(!this.#u(i,o))return;this.#o("dial",a),this.#m(i,"failed")}}#m(e,t,r=0,s=t){if(this.dials.get(e.pubkey)!==e)return;this.dials.delete(e.pubkey),this.discovery.failed(e),this.#ie(e),clearTimeout(e.timer),this.timers.delete(e.timer),this.#de(e.pc,"dial-end",s);try{e.pc.close()}catch{}if(t==="timeout"?this.counters.dialsTimedOut+=1:t==="rejected"?this.counters.dialsRejected+=1:t!=="superseded"&&(this.counters.dialsFailed+=1),t==="superseded")return;let i=t==="rejected"?3e4:6e4;this.cooldowns.set(e.pubkey,Date.now()+(r>0?r:i)),this.#re()}async#yt({from:e,payload:t}){if(this.stopped||t.transport!==jr)return;let r=typeof t.payload?.sdp=="string"?t.payload.sdp:"";if(t.type==="answer"){let d=this.dials.get(e);if(!d?.outgoing||d.requestId!==t.requestId||!r)return;let p=d.negotiation;if(p.answerPending)return;if(this.#g(d.pc,"answer-received","authenticated"),!await this.#x(e,ye(t.payload.ticket)?t.payload.ticket:null,"answerIncoming")){this.#u(d,p)&&this.#m(d,"failed",0,"admission");return}if(!this.#u(d,p)||!d.outgoing||d.requestId!==t.requestId||p.answerPending)return;p.answerPending=!0,this.#g(d.pc,"answer-admitted","accepted"),d.answerAt=I();try{await this.#fe(d,p,async()=>{await d.pc.setRemoteDescription({type:"answer",sdp:r}),this.#u(d,p)&&(this.#g(d.pc,"remote-installed","answer"),this.#Ne(e,t.payload.obj),this.#ze(d,p))})}catch(g){this.#u(d,p)&&(this.#o("answer",g),this.#m(d,"failed"))}return}if(t.type==="reject"){let d=this.dials.get(e);if(!d?.outgoing||d.requestId!==t.requestId)return;let p=this.#pt(t.payload);this.#m(d,"rejected",p.retryAfterMs),this.#$(e,!1),this.#gt(e,p);return}if(t.type!=="offer"||!r||(this.#j(),this.discovery.suppresses(e))||this.banned.has(e)||this.links.has(e))return;let s=`${e}:${t.requestId}`,i=this.dials.get(e);if(i&&!i.outgoing&&i.requestId===t.requestId||this.receivedOffers.has(s)||(this.#g(this.dials.get(e)?.pc,"offer-received","authenticated"),!await this.#x(e,ye(t.payload.ticket)?t.payload.ticket:null,"offerIncoming")||this.stopped||this.links.has(e))||(this.#j(),this.discovery.suppresses(e)))return;let o=this.dials.get(e);if(o&&!o.outgoing&&o.requestId===t.requestId||this.receivedOffers.has(s))return;this.receivedOffers.add(s),this.receivedOffers.size>256&&this.receivedOffers.delete(this.receivedOffers.values().next().value);let a,l=!1;if(o?.outgoing){if(o.negotiation.answerPending||this.session.pubkeythis.options.maxPeers||!["new","connecting"].includes(o.pc.connectionState)||!["new","checking"].includes(o.pc.iceConnectionState)||!["stable","have-local-offer"].includes(o.pc.signalingState)){this.#m(o,"failed");return}a=o,l=!0}else{if(o&&this.#m(o,"superseded"),!this.#_()&&!this.#dt(t.payload?.peers,t.payload?.requestedKey)){this.counters.offersRefused+=1,this.counters.evictionsUnavailable+=1,this.#ue(e,"reject",t.requestId,this.#ft(e));return}let d=this.#He(!1);a={pubkey:e,pc:d,startedAt:I(),offerSentAt:I()},this.dials.set(e,a),a.timer=this.#h(this.options.dialTimeoutMs,()=>this.#m(a,"timeout"))}let c=a.pc,u=this.#De(a,t.requestId,!1);l&&this.#g(c,"negotiation","glare-yield"),this.#g(c,"offer-admitted","accepted"),u.onDataChannel=d=>this.#Ue(a,u,d.channel),c.addEventListener("datachannel",u.onDataChannel);try{await this.#fe(a,u,async()=>{if(l){if(!await this.#x(e,ye(t.payload.ticket)?t.payload.ticket:null,"glareBeforeRollback")){this.#u(a,u)&&this.#m(a,"failed",0,"admission");return}if(!this.#u(a,u))return;if(this.links.size+this.dials.size>this.options.maxPeers||!["new","connecting"].includes(c.connectionState)||!["new","checking"].includes(c.iceConnectionState))throw new Error("Pending connection unavailable.");if(c.signalingState==="have-local-offer"&&(await c.setLocalDescription({type:"rollback"}),!this.#u(a,u)))return;if(this.links.size+this.dials.size>this.options.maxPeers||c.signalingState!=="stable"||!["new","connecting"].includes(c.connectionState)||!["new","checking"].includes(c.iceConnectionState))throw new Error("Pending negotiation unavailable.");if(!await this.#x(e,ye(t.payload.ticket)?t.payload.ticket:null,"glareAfterRollback")){this.#u(a,u)&&this.#m(a,"failed",0,"admission");return}if(!this.#u(a,u))return;if(this.links.size+this.dials.size>this.options.maxPeers||c.signalingState!=="stable"||!["new","connecting"].includes(c.connectionState)||!["new","checking"].includes(c.iceConnectionState))throw new Error("Pending negotiation unavailable.")}if(await c.setRemoteDescription({type:"offer",sdp:r}),!this.#u(a,u))return;this.#g(c,"remote-installed","offer");let d=await c.createAnswer();if(!this.#u(a,u)||(await c.setLocalDescription(d),!this.#u(a,u))||(await io(c,1200,u.controller.signal,f=>{a.negotiation===u&&!u.superseded&&this.#Pe(c,"answer",f)}),!this.#u(a,u)))return;if(!await this.#x(e,ye(t.payload.ticket)?t.payload.ticket:null,"answerBeforeSend")){this.#u(a,u)&&this.#m(a,"failed",0,"admission");return}if(!this.#u(a,u))return;let p=this.#se(),g=this.#ue(e,"answer",t.requestId,{sdp:c.localDescription.sdp,...this.#A()?{obj:2}:{},...p?{ticket:p}:{}});this.#g(c,g?"signal-send":"signal-failed","answer"),g?(this.#Ne(e,t.payload.obj),this.counters.offersAccepted+=1,this.#ze(a,u)):this.#m(a,"failed")})}catch(d){this.#u(a,u)&&(this.#o("offer",d),this.#m(a,"failed"))}}async#bt(e,t,r){if(!this.#u(e,t)||t.channel!==r||!t.ready){if(this.links.get(e.pubkey)?.channel!==r)try{r.close()}catch{}return}this.#g(e.pc,"channel-open","accepted"),this.#ie(e,!1);let s=a=>{if(a.channel!==r)try{a.channel.close()}catch{}};e.pc.addEventListener("datachannel",s),this.dials.delete(e.pubkey),e.discovery&&(this.discovery.counters.opened++,this.#q(e.discovery.window,!1),e.discovery=null),clearTimeout(e.timer),this.timers.delete(e.timer),e.outgoing&&(this.counters.dialsAccepted+=1),this.counters.linksOpened+=1,e.offerSentAt&&je(this.signallingSamples,I()-e.offerSentAt);let i=this.#lt({pubkey:e.pubkey,pc:e.pc,channel:r,maxSegmentBytes:this.options.maxSegmentBytes,onRequest:(a,l,c)=>this.#st(a,l,c),onHaveChange:(a,l)=>{for(let c of[...this.haveWaiters])c(l);this.#k()},onScheduleChange:()=>{for(let a of[...this.haveWaiters])a();for(let a of[...this.peerLeaseWaiters])a();this.#k()},onUploadCancelled:(a,l)=>{this.counters.uploadsCancelled+=1,this.counters.uploadCancelledBytes+=l,this.uploadTokens=Math.min(this.options.maxUploadBytesPerSecond*2,this.uploadTokens+l),this.uploadPacer?.recheck()},onClose:a=>{this.uploadPacer?.cancel(a),this.peerLeases.delete(a);for(let l of[...this.peerLeaseWaiters])l();e.pc.removeEventListener("datachannel",s),this.#de(e.pc,"link-close",a.closeReason),this.peerSelection.forget(a),this.links.get(a.pubkey)===a&&(this.links.delete(a.pubkey),this.discovery.forget(a.pubkey),this.counters.linksClosed+=1,this.#n("reannounce",()=>this.#Be()))}});this.links.set(e.pubkey,i),this.#qe(e.pubkey),this.#k(),this.firstLinkAtMs===null&&(this.firstLinkAtMs=Date.now()-this.startedAt),i.sendContribution(this.#p(),this.rendition);for(let a of this.renditions.keys())a!==this.rendition&&i.sendContribution(this.#p(),a);if(this.#p()){i.sendHave([...this.held.keys()]);for(let a of this.originFetches.keys())i.sendFetching(a,2e3)}let o=await xl(e.pc);this.pairTypes[o]=(this.pairTypes[o]||0)+1;for(let a of[...this.haveWaiters])a()}};var Nh=Object.freeze({version:"0.4.4",sourceCommit:"d4a1235b035b4244ea73b55b1da0d4f88f64c376"});export{Ti as KIND_SEGMENT_COMMITMENT,Oi as commitmentContent,xt as commitmentPieceSize,kl as createHlsSwarm,vr as finalizeEvent,Yt as generateSecretKey,Jt as matchFilter,Nh as relayswarmBuild,Ot as segmentMediaContext,Zt as verifyEvent}; +/*! RelaySwarm 0.4.4; public source c8120c5bf8c117e334a37a072b3bd6f3de46cc3a. See media-peer-demo.NOTICE.txt. */ +function ns(n,e){try{let t=a=>{if(!n)return null;let l=typeof n.getResponseHeader=="function"?n.getResponseHeader(a):n.headers?.get?.(a);return typeof l=="string"?l:null},r=t("Date"),s=typeof r=="string"&&/\sGMT$/u.test(r.trim())?Date.parse(r):NaN;if(!Number.isFinite(s))return null;let i=Number(t("Age")),o=s+(Number.isFinite(i)&&i>0?i*1e3:0)-e;return Number.isFinite(o)&&Math.abs(o)<=6048e5?o:null}catch{return null}}function ss(n){return{samples:n.length,offsetSeconds:n.length?Math.round(Math.max(...n)/1e3):null}}function Ft(n){return n instanceof Uint8Array||ArrayBuffer.isView(n)&&n.constructor.name==="Uint8Array"}function Pe(n,e=""){if(!Number.isSafeInteger(n)||n<0){let t=e&&`"${e}" `;throw new Error(`${t}expected integer >= 0, got ${n}`)}}function ae(n,e,t=""){let r=Ft(n),s=n?.length,i=e!==void 0;if(!r||i&&s!==e){let o=t&&`"${t}" `,a=i?` of length ${e}`:"",l=r?`length=${s}`:`type=${typeof n}`;throw new Error(o+"expected Uint8Array"+a+", got "+l)}return n}function pt(n){if(typeof n!="function"||typeof n.create!="function")throw new Error("Hash must wrapped by utils.createHasher");Pe(n.outputLen),Pe(n.blockLen)}function At(n,e=!0){if(n.destroyed)throw new Error("Hash instance has been destroyed");if(e&&n.finished)throw new Error("Hash#digest() has already been called")}function os(n,e){ae(n,void 0,"digestInto() output");let t=e.outputLen;if(n.length='+t)}function Ge(...n){for(let e=0;e>>e}var as=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",lo=Array.from({length:256},(n,e)=>e.toString(16).padStart(2,"0"));function He(n){if(ae(n),as)return n.toHex();let e="";for(let t=0;t=$e._0&&n<=$e._9)return n-$e._0;if(n>=$e.A&&n<=$e.F)return n-($e.A-10);if(n>=$e.a&&n<=$e.f)return n-($e.a-10)}function Te(n){if(typeof n!="string")throw new Error("hex string expected, got "+typeof n);if(as)return Uint8Array.fromHex(n);let e=n.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let r=new Uint8Array(t);for(let s=0,i=0;sn(i).update(s).digest(),r=n(void 0);return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=s=>n(s),Object.assign(t,e),Object.freeze(t)}function Ye(n=32){let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(n))}var cs=n=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,n])});function hs(n,e,t){return n&e^~n&t}function us(n,e,t){return n&e^n&t^e&t}var ar=class{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,r,s){this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=s,this.buffer=new Uint8Array(e),this.view=or(this.buffer)}update(e){At(this),ae(e);let{view:t,buffer:r,blockLen:s}=this,i=e.length;for(let o=0;os-o&&(this.process(r,0),o=0);for(let d=o;du.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d>>3,m=Ue(g,17)^Ue(g,19)^g>>>10;rt[d]=m+rt[d-7]+p+rt[d-16]|0}let{A:r,B:s,C:i,D:o,E:a,F:l,G:c,H:u}=this;for(let d=0;d<64;d++){let f=Ue(a,6)^Ue(a,11)^Ue(a,25),g=u+f+hs(a,l,c)+co[d]+rt[d]|0,m=(Ue(r,2)^Ue(r,13)^Ue(r,22))+us(r,s,i)|0;u=c,c=l,l=a,a=o+g|0,o=i,i=s,s=r,r=g+m|0}r=r+this.A|0,s=s+this.B|0,i=i+this.C|0,o=o+this.D|0,a=a+this.E|0,l=l+this.F|0,c=c+this.G|0,u=u+this.H|0,this.set(r,s,i,o,a,l,c,u)}roundClean(){Ge(rt)}destroy(){this.set(0,0,0,0,0,0,0,0),Ge(this.buffer)}},Qr=class extends Jr{A=Ze[0]|0;B=Ze[1]|0;C=Ze[2]|0;D=Ze[3]|0;E=Ze[4]|0;F=Ze[5]|0;G=Ze[6]|0;H=Ze[7]|0;constructor(){super(32)}};var qe=ls(()=>new Qr,cs(1));var tn=BigInt(0),en=BigInt(1);function qt(n,e=""){if(typeof n!="boolean"){let t=e&&`"${e}" `;throw new Error(t+"expected boolean, got type="+typeof n)}return n}function ds(n){if(typeof n=="bigint"){if(!lr(n))throw new Error("positive bigint expected, got "+n)}else Pe(n);return n}function jt(n){let e=ds(n).toString(16);return e.length&1?"0"+e:e}function fs(n){if(typeof n!="string")throw new Error("hex string expected, got "+typeof n);return n===""?tn:BigInt("0x"+n)}function nt(n){return fs(He(n))}function rn(n){return fs(He(ho(ae(n)).reverse()))}function cr(n,e){Pe(e),n=ds(n);let t=Te(n.toString(16).padStart(e*2,"0"));if(t.length!==e)throw new Error("number too large");return t}function nn(n,e){return cr(n,e).reverse()}function ho(n){return Uint8Array.from(n)}function ps(n){return Uint8Array.from(n,(e,t)=>{let r=e.charCodeAt(0);if(e.length!==1||r>127)throw new Error(`string contains non-ASCII character "${n[t]}" with code ${r} at position ${t}`);return r})}var lr=n=>typeof n=="bigint"&&tn<=n;function uo(n,e,t){return lr(n)&&lr(e)&&lr(t)&&e<=n&&ntn;n>>=en,e+=1);return e}var Wt=n=>(en<new Uint8Array(b),s=Uint8Array.of(),i=Uint8Array.of(0),o=Uint8Array.of(1),a=1e3,l=r(n),c=r(n),u=0,d=()=>{l.fill(1),c.fill(0),u=0},f=(...b)=>t(c,be(l,...b)),g=(b=s)=>{c=f(i,b),l=f(),b.length!==0&&(c=f(o,b),l=f())},p=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let b=0,v=[];for(;b{d(),g(b);let w;for(;!(w=v(p()));)g();return d(),w}}function Kt(n,e={},t={}){if(!n||typeof n!="object")throw new Error("expected valid options object");function r(i,o,a){let l=n[i];if(a&&l===void 0)return;let c=typeof l;if(c!==o||l===null)throw new Error(`param "${i}" is invalid: expected ${o}, got ${c}`)}let s=(i,o)=>Object.entries(i).forEach(([a,l])=>r(a,l,o));s(e,!1),s(t,!0)}function on(n){let e=new WeakMap;return(t,...r)=>{let s=e.get(t);if(s!==void 0)return s;let i=n(t,...r);return e.set(t,i),i}}var Me=BigInt(0),Ae=BigInt(1),gt=BigInt(2),ws=BigInt(3),vs=BigInt(4),xs=BigInt(5),fo=BigInt(7),Ss=BigInt(8),po=BigInt(9),Es=BigInt(16);function ze(n,e){let t=n%e;return t>=Me?t:e+t}function _e(n,e,t){let r=n;for(;e-- >Me;)r*=r,r%=t;return r}function ys(n,e){if(n===Me)throw new Error("invert: expected non-zero number");if(e<=Me)throw new Error("invert: expected positive modulus, got "+e);let t=ze(n,e),r=e,s=Me,i=Ae,o=Ae,a=Me;for(;t!==Me;){let c=r/t,u=r%t,d=s-o*c,f=i-a*c;r=t,t=u,s=o,i=a,o=d,a=f}if(r!==Ae)throw new Error("invert: does not exist");return ze(s,e)}function ln(n,e,t){if(!n.eql(n.sqr(e),t))throw new Error("Cannot find square root")}function As(n,e){let t=(n.ORDER+Ae)/vs,r=n.pow(e,t);return ln(n,r,e),r}function go(n,e){let t=(n.ORDER-xs)/Ss,r=n.mul(e,gt),s=n.pow(r,t),i=n.mul(e,s),o=n.mul(n.mul(i,gt),s),a=n.mul(i,n.sub(o,n.ONE));return ln(n,a,e),a}function mo(n){let e=kt(n),t=ks(n),r=t(e,e.neg(e.ONE)),s=t(e,r),i=t(e,e.neg(r)),o=(n+fo)/Es;return(a,l)=>{let c=a.pow(l,o),u=a.mul(c,r),d=a.mul(c,s),f=a.mul(c,i),g=a.eql(a.sqr(u),l),p=a.eql(a.sqr(d),l);c=a.cmov(c,u,g),u=a.cmov(f,d,p);let m=a.eql(a.sqr(u),l),b=a.cmov(c,u,m);return ln(a,b,l),b}}function ks(n){if(n1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return As;let i=s.pow(r,e),o=(e+Ae)/gt;return function(l,c){if(l.is0(c))return c;if(bs(l,c)!==1)throw new Error("Cannot find square root");let u=t,d=l.mul(l.ONE,i),f=l.pow(c,e),g=l.pow(c,o);for(;!l.eql(f,l.ONE);){if(l.is0(f))return l.ZERO;let p=1,m=l.sqr(f);for(;!l.eql(m,l.ONE);)if(p++,m=l.sqr(m),p===u)throw new Error("Cannot find square root");let b=Ae<(r[s]="function",r),e);return Kt(n,t),n}function wo(n,e,t){if(tMe;)t&Ae&&(r=n.mul(r,s)),s=n.sqr(s),t>>=Ae;return r}function hr(n,e,t=!1){let r=new Array(e.length).fill(t?n.ZERO:void 0),s=e.reduce((o,a,l)=>n.is0(a)?o:(r[l]=o,n.mul(o,a)),n.ONE),i=n.inv(s);return e.reduceRight((o,a,l)=>n.is0(a)?o:(r[l]=n.mul(o,r[l]),n.mul(o,a)),i),r}function bs(n,e){let t=(n.ORDER-Ae)/gt,r=n.pow(e,t),s=n.eql(r,n.ONE),i=n.eql(r,n.ZERO),o=n.eql(r,n.neg(n.ONE));if(!s&&!i&&!o)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function vo(n,e){e!==void 0&&Pe(e);let t=e!==void 0?e:n.toString(2).length,r=Math.ceil(t/8);return{nBitLength:t,nByteLength:r}}var an=class{ORDER;BITS;BYTES;isLE;ZERO=Me;ONE=Ae;_lengths;_sqrt;_mod;constructor(e,t={}){if(e<=Me)throw new Error("invalid field: expected ORDER > 0, got "+e);let r;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(r=t.BITS),typeof t.sqrt=="function"&&(this.sqrt=t.sqrt),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=t.allowedLengths?.slice()),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:s,nByteLength:i}=vo(e,r);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=s,this.BYTES=i,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return ze(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return Me<=e&&es)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);let c=new Uint8Array(s);c.set(e,i?0:c.length-e.length),e=c}if(e.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+e.length);let l=i?rn(e):nt(e);if(a&&(l=ze(l,o)),!t&&!this.isValid(l))throw new Error("invalid field element: outside of range 0..ORDER");return l}invertBatch(e){return hr(this,e)}cmov(e,t,r){return r?t:e}};function kt(n,e={}){return new an(n,e)}function Ms(n){if(typeof n!="bigint")throw new Error("field order must be bigint");let e=n.toString(2).length;return Math.ceil(e/8)}function hn(n){let e=Ms(n);return e+Math.ceil(e/2)}function ur(n,e,t=!1){ae(n);let r=n.length,s=Ms(e),i=hn(e);if(r<16||r1024)throw new Error("expected "+i+"-1024 bytes of input, got "+r);let o=t?rn(n):nt(n),a=ze(o,e-Ae)+Ae;return t?nn(a,s):cr(a,s)}var Mt=BigInt(0),mt=BigInt(1);function Vt(n,e){let t=e.negate();return n?t:e}function pn(n,e){let t=hr(n.Fp,e.map(r=>r.Z));return e.map((r,s)=>n.fromAffine(r.toAffine(t[s])))}function Ls(n,e){if(!Number.isSafeInteger(n)||n<=0||n>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+n)}function un(n,e){Ls(n,e);let t=Math.ceil(e/n)+1,r=2**(n-1),s=2**n,i=Wt(n),o=BigInt(n);return{windows:t,windowSize:r,mask:i,maxNumber:s,shiftBy:o}}function Bs(n,e,t){let{windowSize:r,mask:s,maxNumber:i,shiftBy:o}=t,a=Number(n&s),l=n>>o;a>r&&(a-=i,l+=mt);let c=e*r,u=c+Math.abs(a)-1,d=a===0,f=a<0,g=e%2!==0;return{nextN:l,offset:u,isZero:d,isNeg:f,isNegF:g,offsetF:c}}var dn=new WeakMap,_s=new WeakMap;function fn(n){return _s.get(n)||1}function Rs(n){if(n!==Mt)throw new Error("invalid wNAF")}var dr=class{BASE;ZERO;Fn;bits;constructor(e,t){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,r=this.ZERO){let s=e;for(;t>Mt;)t&mt&&(r=r.add(s)),s=s.double(),t>>=mt;return r}precomputeWindow(e,t){let{windows:r,windowSize:s}=un(t,this.bits),i=[],o=e,a=o;for(let l=0;lMt||r>Mt;)t&mt&&(i=i.add(s)),r&mt&&(o=o.add(s)),s=s.double(),t>>=mt,r>>=mt;return{p1:i,p2:o}}function Ts(n,e,t){if(e){if(e.ORDER!==n)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return cn(e),e}else return kt(n,{isLE:t})}function Is(n,e,t={},r){if(r===void 0&&(r=n==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${n} CURVE object`);for(let l of["p","n","h"]){let c=e[l];if(!(typeof c=="bigint"&&c>Mt))throw new Error(`CURVE.${l} must be positive bigint`)}let s=Ts(e.p,t.Fp,r),i=Ts(e.n,t.Fn,r),a=["Gx","Gy","a",n==="weierstrass"?"b":"d"];for(let l of a)if(!s.isValid(e[l]))throw new Error(`CURVE.${l} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:s,Fn:i}}function fr(n,e){return function(r){let s=n(r);return{secretKey:s,publicKey:e(s)}}}var pr=class{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,t){if(pt(e),ae(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let r=this.blockLen,s=new Uint8Array(r);s.set(t.length>r?e.create().update(t).digest():t);for(let i=0;inew pr(n,e).update(t).digest();st.create=(n,e)=>new pr(n,e);var Cs=(n,e)=>(n+(n>=0?e:-e)/Ns)/e;function xo(n,e,t){let[[r,s],[i,o]]=e,a=Cs(o*n,t),l=Cs(-s*n,t),c=n-a*r-l*i,u=-a*s-l*o,d=c=g||u=g)throw new Error("splitScalar (endomorphism): failed, k="+n);return{k1neg:d,k1:c,k2neg:f,k2:u}}function mn(n){if(!["compact","recovered","der"].includes(n))throw new Error('Signature format must be "compact", "recovered", or "der"');return n}function gn(n,e){let t={};for(let r of Object.keys(e))t[r]=n[r]===void 0?e[r]:n[r];return qt(t.lowS,"lowS"),qt(t.prehash,"prehash"),t.format!==void 0&&mn(t.format),t}var yn=class extends Error{constructor(e=""){super(e)}},it={Err:yn,_tlv:{encode:(n,e)=>{let{Err:t}=it;if(n<0||n>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");let r=e.length/2,s=jt(r);if(s.length/2&128)throw new t("tlv.encode: long form length too big");let i=r>127?jt(s.length/2|128):"";return jt(n)+i+s+e},decode(n,e){let{Err:t}=it,r=0;if(n<0||n>256)throw new t("tlv.encode: wrong tag");if(e.length<2||e[r++]!==n)throw new t("tlv.decode: wrong tlv");let s=e[r++],i=!!(s&128),o=0;if(!i)o=s;else{let l=s&127;if(!l)throw new t("tlv.decode(long): indefinite length not supported");if(l>4)throw new t("tlv.decode(long): byte length is too big");let c=e.subarray(r,r+l);if(c.length!==l)throw new t("tlv.decode: length bytes not complete");if(c[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let u of c)o=o<<8|u;if(r+=l,o<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(r,r+o);if(a.length!==o)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(r+o)}}},_int:{encode(n){let{Err:e}=it;if(n{let{X:x,Y:S,Z:M}=N;if(r.eql(M,r.ONE))return{x,y:S};let H=N.is0();h==null&&(h=H?r.ONE:r.inv(M));let D=r.mul(x,h),B=r.mul(S,h),U=r.mul(M,h);if(H)return{x:r.ZERO,y:r.ZERO};if(!r.eql(U,r.ONE))throw new Error("invZ was invalid");return{x:D,y:B}}),k=on(N=>{if(N.is0()){if(e.allowInfinityPoint&&!r.is0(N.Y))return;throw new Error("bad point: ZERO")}let{x:h,y:x}=N.toAffine();if(!r.isValid(h)||!r.isValid(x))throw new Error("bad point: x or y not field elements");if(!b(h,x))throw new Error("bad point: equation left != right");if(!N.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function W(N,h,x,S,M){return x=new _(r.mul(x.X,N),x.Y,x.Z),h=Vt(S,h),x=Vt(M,x),h.add(x)}class _{static BASE=new _(i.Gx,i.Gy,r.ONE);static ZERO=new _(r.ZERO,r.ONE,r.ZERO);static Fp=r;static Fn=s;X;Y;Z;constructor(h,x,S){this.X=T("x",h),this.Y=T("y",x,!0),this.Z=T("z",S),Object.freeze(this)}static CURVE(){return i}static fromAffine(h){let{x,y:S}=h||{};if(!h||!r.isValid(x)||!r.isValid(S))throw new Error("invalid affine point");if(h instanceof _)throw new Error("projective point not allowed");return r.is0(x)&&r.is0(S)?_.ZERO:new _(x,S,r.ONE)}static fromBytes(h){let x=_.fromAffine(p(ae(h,void 0,"point")));return x.assertValidity(),x}static fromHex(h){return _.fromBytes(Te(h))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(h=8,x=!0){return P.createCache(this,h),x||this.multiply(gr),this}assertValidity(){k(this)}hasEvenY(){let{y:h}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(h)}equals(h){O(h);let{X:x,Y:S,Z:M}=this,{X:H,Y:D,Z:B}=h,U=r.eql(r.mul(x,B),r.mul(H,M)),C=r.eql(r.mul(S,B),r.mul(D,M));return U&&C}negate(){return new _(this.X,r.neg(this.Y),this.Z)}double(){let{a:h,b:x}=i,S=r.mul(x,gr),{X:M,Y:H,Z:D}=this,B=r.ZERO,U=r.ZERO,C=r.ZERO,z=r.mul(M,M),ee=r.mul(H,H),te=r.mul(D,D),$=r.mul(M,H);return $=r.add($,$),C=r.mul(M,D),C=r.add(C,C),B=r.mul(h,C),U=r.mul(S,te),U=r.add(B,U),B=r.sub(ee,U),U=r.add(ee,U),U=r.mul(B,U),B=r.mul($,B),C=r.mul(S,C),te=r.mul(h,te),$=r.sub(z,te),$=r.mul(h,$),$=r.add($,C),C=r.add(z,z),z=r.add(C,z),z=r.add(z,te),z=r.mul(z,$),U=r.add(U,z),te=r.mul(H,D),te=r.add(te,te),z=r.mul(te,$),B=r.sub(B,z),C=r.mul(te,ee),C=r.add(C,C),C=r.add(C,C),new _(B,U,C)}add(h){O(h);let{X:x,Y:S,Z:M}=this,{X:H,Y:D,Z:B}=h,U=r.ZERO,C=r.ZERO,z=r.ZERO,ee=i.a,te=r.mul(i.b,gr),$=r.mul(x,H),ne=r.mul(S,D),ue=r.mul(M,B),Z=r.add(x,S),oe=r.add(H,D);Z=r.mul(Z,oe),oe=r.add($,ne),Z=r.sub(Z,oe),oe=r.add(x,M);let ge=r.add(H,B);return oe=r.mul(oe,ge),ge=r.add($,ue),oe=r.sub(oe,ge),ge=r.add(S,M),U=r.add(D,B),ge=r.mul(ge,U),U=r.add(ne,ue),ge=r.sub(ge,U),z=r.mul(ee,oe),U=r.mul(te,ue),z=r.add(U,z),U=r.sub(ne,z),z=r.add(ne,z),C=r.mul(U,z),ne=r.add($,$),ne=r.add(ne,$),ue=r.mul(ee,ue),oe=r.mul(te,oe),ne=r.add(ne,ue),ue=r.sub($,ue),ue=r.mul(ee,ue),oe=r.add(oe,ue),$=r.mul(ne,oe),C=r.add(C,$),$=r.mul(ge,oe),U=r.mul(Z,U),U=r.sub(U,$),$=r.mul(Z,ne),z=r.mul(ge,z),z=r.add(z,$),new _(U,C,z)}subtract(h){return this.add(h.negate())}is0(){return this.equals(_.ZERO)}multiply(h){let{endo:x}=e;if(!s.isValidNot0(h))throw new Error("invalid scalar: out of range");let S,M,H=D=>P.cached(this,D,B=>pn(_,B));if(x){let{k1neg:D,k1:B,k2neg:U,k2:C}=K(h),{p:z,f:ee}=H(B),{p:te,f:$}=H(C);M=ee.add($),S=W(x.beta,z,te,D,U)}else{let{p:D,f:B}=H(h);S=D,M=B}return pn(_,[S,M])[0]}multiplyUnsafe(h){let{endo:x}=e,S=this;if(!s.isValid(h))throw new Error("invalid scalar: out of range");if(h===Xe||S.is0())return _.ZERO;if(h===Bt)return S;if(P.hasCache(this))return this.multiply(h);if(x){let{k1neg:M,k1:H,k2neg:D,k2:B}=K(h),{p1:U,p2:C}=Os(_,S,H,B);return W(x.beta,U,C,M,D)}else return P.unsafe(S,h)}toAffine(h){return A(this,h)}isTorsionFree(){let{isTorsionFree:h}=e;return o===Bt?!0:h?h(_,this):P.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:h}=e;return o===Bt?this:h?h(_,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(h=!0){return qt(h,"isCompressed"),this.assertValidity(),g(_,this,h)}toHex(h=!0){return He(this.toBytes(h))}toString(){return``}}let F=s.BITS,P=new dr(_,e.endo?Math.ceil(F/2):F);return _.BASE.precompute(8),_}function Hs(n){return Uint8Array.of(n?2:3)}function Ds(n,e){return{secretKey:e.BYTES,publicKey:1+n.BYTES,publicKeyUncompressed:1+2*n.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Eo(n,e={}){let{Fn:t}=n,r=e.randomBytes||Ye,s=Object.assign(Ds(n.Fp,t),{seed:hn(t.ORDER)});function i(g){try{let p=t.fromBytes(g);return t.isValidNot0(p)}catch{return!1}}function o(g,p){let{publicKey:m,publicKeyUncompressed:b}=s;try{let v=g.length;return p===!0&&v!==m||p===!1&&v!==b?!1:!!n.fromBytes(g)}catch{return!1}}function a(g=r(s.seed)){return ur(ae(g,s.seed,"seed"),t.ORDER)}function l(g,p=!0){return n.BASE.multiply(t.fromBytes(g)).toBytes(p)}function c(g){let{secretKey:p,publicKey:m,publicKeyUncompressed:b}=s;if(!Ft(g)||"_lengths"in t&&t._lengths||p===m)return;let v=ae(g,void 0,"key").length;return v===m||v===b}function u(g,p,m=!0){if(c(g)===!0)throw new Error("first arg must be private key");if(c(p)===!1)throw new Error("second arg must be public key");let b=t.fromBytes(g);return n.fromBytes(p).multiply(b).toBytes(m)}let d={isValidSecretKey:i,isValidPublicKey:o,randomSecretKey:a},f=fr(a,l);return Object.freeze({getPublicKey:l,getSharedSecret:u,keygen:f,Point:n,utils:d,lengths:s})}function Us(n,e,t={}){pt(e),Kt(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),t=Object.assign({},t);let r=t.randomBytes||Ye,s=t.hmac||((x,S)=>st(e,x,S)),{Fp:i,Fn:o}=n,{ORDER:a,BITS:l}=o,{keygen:c,getPublicKey:u,getSharedSecret:d,utils:f,lengths:g}=Eo(n,t),p={prehash:!0,lowS:typeof t.lowS=="boolean"?t.lowS:!0,format:"compact",extraEntropy:!1},m=a*Ns>Bt;return x>S}function v(x,S){if(!o.isValidNot0(S))throw new Error(`invalid signature ${x}: out of range 1..Point.Fn.ORDER`);return S}function w(){if(m)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function T(x,S){mn(S);let M=g.signature,H=S==="compact"?M:S==="recovered"?M+1:void 0;return ae(x,H)}class O{r;s;recovery;constructor(S,M,H){if(this.r=v("r",S),this.s=v("s",M),H!=null){if(w(),![0,1,2,3].includes(H))throw new Error("invalid recovery id");this.recovery=H}Object.freeze(this)}static fromBytes(S,M=p.format){T(S,M);let H;if(M==="der"){let{r:C,s:z}=it.toSig(ae(S));return new O(C,z)}M==="recovered"&&(H=S[0],M="compact",S=S.subarray(1));let D=g.signature/2,B=S.subarray(0,D),U=S.subarray(D,D*2);return new O(o.fromBytes(B),o.fromBytes(U),H)}static fromHex(S,M){return this.fromBytes(Te(S),M)}assertRecovery(){let{recovery:S}=this;if(S==null)throw new Error("invalid recovery id: must be present");return S}addRecoveryBit(S){return new O(this.r,this.s,S)}recoverPublicKey(S){let{r:M,s:H}=this,D=this.assertRecovery(),B=D===2||D===3?M+a:M;if(!i.isValid(B))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let U=i.toBytes(B),C=n.fromBytes(be(Hs((D&1)===0),U)),z=o.inv(B),ee=A(ae(S,void 0,"msgHash")),te=o.create(-ee*z),$=o.create(H*z),ne=n.BASE.multiplyUnsafe(te).add(C.multiplyUnsafe($));if(ne.is0())throw new Error("invalid recovery: point at infinify");return ne.assertValidity(),ne}hasHighS(){return b(this.s)}toBytes(S=p.format){if(mn(S),S==="der")return Te(it.hexFromSig(this));let{r:M,s:H}=this,D=o.toBytes(M),B=o.toBytes(H);return S==="recovered"?(w(),be(Uint8Array.of(this.assertRecovery()),D,B)):be(D,B)}toHex(S){return He(this.toBytes(S))}}let K=t.bits2int||function(S){if(S.length>8192)throw new Error("input is too large");let M=nt(S),H=S.length*8-l;return H>0?M>>BigInt(H):M},A=t.bits2int_modN||function(S){return o.create(K(S))},k=Wt(l);function W(x){return gs("num < 2^"+l,x,Xe,k),o.toBytes(x)}function _(x,S){return ae(x,void 0,"message"),S?ae(e(x),void 0,"prehashed message"):x}function F(x,S,M){let{lowS:H,prehash:D,extraEntropy:B}=gn(M,p);x=_(x,D);let U=A(x),C=o.fromBytes(S);if(!o.isValidNot0(C))throw new Error("invalid private key");let z=[W(C),W(U)];if(B!=null&&B!==!1){let ne=B===!0?r(g.secretKey):B;z.push(ae(ne,void 0,"extraEntropy"))}let ee=be(...z),te=U;function $(ne){let ue=K(ne);if(!o.isValidNot0(ue))return;let Z=o.inv(ue),oe=n.BASE.multiply(ue).toAffine(),ge=o.create(oe.x);if(ge===Xe)return;let Ie=o.create(Z*o.create(te+ge*C));if(Ie===Xe)return;let Ke=(oe.x===ge?0:2)|Number(oe.y&Bt),Ee=Ie;return H&&b(Ie)&&(Ee=o.neg(Ie),Ke^=1),new O(ge,Ee,m?void 0:Ke)}return{seed:ee,k2sig:$}}function P(x,S,M={}){let{seed:H,k2sig:D}=F(x,S,M);return ms(e.outputLen,o.BYTES,s)(H,D).toBytes(M.format)}function N(x,S,M,H={}){let{lowS:D,prehash:B,format:U}=gn(H,p);if(M=ae(M,void 0,"publicKey"),S=_(S,B),!Ft(x)){let C=x instanceof O?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+C)}T(x,U);try{let C=O.fromBytes(x,U),z=n.fromBytes(M);if(D&&C.hasHighS())return!1;let{r:ee,s:te}=C,$=A(S),ne=o.inv(te),ue=o.create($*ne),Z=o.create(ee*ne),oe=n.BASE.multiplyUnsafe(ue).add(z.multiplyUnsafe(Z));return oe.is0()?!1:o.create(oe.x)===ee}catch{return!1}}function h(x,S,M={}){let{prehash:H}=gn(M,p);return S=_(S,H),O.fromBytes(x,"recovered").recoverPublicKey(S).toBytes()}return Object.freeze({keygen:c,getPublicKey:u,getSharedSecret:d,utils:f,lengths:g,Point:n,sign:P,verify:N,recoverPublicKey:h,Signature:O,hash:e})}var br={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Ao={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},ko=BigInt(0),bn=BigInt(2);function Mo(n){let e=br.p,t=BigInt(3),r=BigInt(6),s=BigInt(11),i=BigInt(22),o=BigInt(23),a=BigInt(44),l=BigInt(88),c=n*n*n%e,u=c*c*n%e,d=_e(u,t,e)*u%e,f=_e(d,t,e)*u%e,g=_e(f,bn,e)*c%e,p=_e(g,s,e)*g%e,m=_e(p,i,e)*p%e,b=_e(m,a,e)*m%e,v=_e(b,l,e)*b%e,w=_e(v,a,e)*m%e,T=_e(w,t,e)*u%e,O=_e(T,o,e)*p%e,K=_e(O,r,e)*c%e,A=_e(K,bn,e);if(!mr.eql(mr.sqr(A),n))throw new Error("Cannot find square root");return A}var mr=kt(br.p,{sqrt:Mo}),yt=Ps(br,{Fp:mr,endo:Ao}),qs=Us(yt,qe),zs={};function yr(n,...e){let t=zs[n];if(t===void 0){let r=qe(ps(n));t=be(r,r),zs[n]=t}return qe(be(t,...e))}var vn=n=>n.toBytes(!0).slice(1),xn=n=>n%bn===ko;function wn(n){let{Fn:e,BASE:t}=yt,r=e.fromBytes(n),s=t.multiply(r);return{scalar:xn(s.y)?r:e.neg(r),bytes:vn(s)}}function js(n){let e=mr;if(!e.isValidNot0(n))throw new Error("invalid x: Fail if x \u2265 p");let t=e.create(n*n),r=e.create(t*n+BigInt(7)),s=e.sqrt(r);xn(s)||(s=e.neg(s));let i=yt.fromAffine({x:n,y:s});return i.assertValidity(),i}var $t=nt;function Ws(...n){return yt.Fn.create($t(yr("BIP0340/challenge",...n)))}function Fs(n){return wn(n).bytes}function Bo(n,e,t=Ye(32)){let{Fn:r}=yt,s=ae(n,void 0,"message"),{bytes:i,scalar:o}=wn(e),a=ae(t,32,"auxRand"),l=r.toBytes(o^$t(yr("BIP0340/aux",a))),c=yr("BIP0340/nonce",l,i,s),{bytes:u,scalar:d}=wn(c),f=Ws(u,i,s),g=new Uint8Array(64);if(g.set(u,0),g.set(r.toBytes(r.create(d+f*o)),32),!Ks(g,s,i))throw new Error("sign: Invalid signature produced");return g}function Ks(n,e,t){let{Fp:r,Fn:s,BASE:i}=yt,o=ae(n,64,"signature"),a=ae(e,void 0,"message"),l=ae(t,32,"publicKey");try{let c=js($t(l)),u=$t(o.subarray(0,32));if(!r.isValidNot0(u))return!1;let d=$t(o.subarray(32,64));if(!s.isValidNot0(d))return!1;let f=Ws(s.toBytes(u),vn(c),a),g=i.multiplyUnsafe(d).add(c.multiplyUnsafe(s.neg(f))),{x:p,y:m}=g.toAffine();return!(g.is0()||!xn(m)||p!==u)}catch{return!1}}var Rt=(()=>{let t=(r=Ye(48))=>ur(r,br.n);return{keygen:fr(t,Fs),getPublicKey:Fs,sign:Bo,verify:Ks,Point:yt,utils:{randomSecretKey:t,taggedHash:yr,lift_x:js,pointToBytes:vn},lengths:{secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:64,seed:48}}})();var lc=new TextDecoder("utf-8"),Ro=new TextEncoder;function To(n){for(let e=0;e<64;e++){let t=n.charCodeAt(e);if(isNaN(t)||t<48||t>102||t>57&&t<97)return!1}return!0}var Tt=Symbol("verified"),Lo=n=>n instanceof Object;function _o(n){if(!Lo(n)||typeof n.kind!="number"||typeof n.content!="string"||typeof n.created_at!="number"||typeof n.pubkey!="string"||!To(n.pubkey)||!Array.isArray(n.tags))return!1;for(let e=0;e{function t(r,...s){if(we(r,void 0,"key"),!Po)throw new Error("Non little-endian hardware is not yet supported");if(n.nonceLength!==void 0){let u=s[0];we(u,n.varSizeNonce?void 0:n.nonceLength,"nonce")}let i=n.tagLength;i&&s[1]!==void 0&&we(s[1],void 0,"AAD");let o=e(r,...s),a=(u,d)=>{if(d!==void 0){if(u!==2)throw new Error("cipher output not supported");we(d,void 0,"output")}},l=!1;return{encrypt(u,d){if(l)throw new Error("cannot encrypt() twice with same key + nonce");return l=!0,we(u),a(o.encrypt.length,d),o.encrypt(u,d)},decrypt(u,d){if(we(u),i&&u.lengthUint8Array.from(n.split(""),e=>e.charCodeAt(0)),Do=Xs("expand 16-byte k"),Uo=Xs("expand 32-byte k"),zo=Je(Do),Fo=Je(Uo);function G(n,e){return n<>>32-e}function kn(n){return n.byteOffset%4===0}var Ar=64,qo=16,Js=2**32-1,Zs=Uint32Array.of();function jo(n,e,t,r,s,i,o,a){let l=s.length,c=new Uint8Array(Ar),u=Je(c),d=kn(s)&&kn(i),f=d?Je(s):Zs,g=d?Je(i):Zs;for(let p=0;p=Js)throw new Error("arx: counter overflow");let m=Math.min(Ar,l-p);if(d&&m===Ar){let b=p/4;if(p%4!==0)throw new Error("arx: invalid block position");for(let v=0,w;v{we(a,void 0,"key"),we(l,void 0,"nonce"),we(c,void 0,"data");let f=c.length;if(u===void 0&&(u=new Uint8Array(f)),we(u,void 0,"output"),Sr(d),d<0||d>=Js)throw new Error("arx: counter overflow");if(u.length>>13|r<<3)&8191,this.r[2]=(r>>>10|s<<6)&7939,this.r[3]=(s>>>7|i<<9)&8191,this.r[4]=(i>>>4|o<<12)&255,this.r[5]=o>>>1&8190,this.r[6]=(o>>>14|a<<2)&8191,this.r[7]=(a>>>11|l<<5)&8065,this.r[8]=(l>>>8|c<<8)&8191,this.r[9]=c>>>5&127;for(let u=0;u<8;u++)this.pad[u]=xe(e,16+2*u)}process(e,t,r=!1){let s=r?0:2048,{h:i,r:o}=this,a=o[0],l=o[1],c=o[2],u=o[3],d=o[4],f=o[5],g=o[6],p=o[7],m=o[8],b=o[9],v=xe(e,t+0),w=xe(e,t+2),T=xe(e,t+4),O=xe(e,t+6),K=xe(e,t+8),A=xe(e,t+10),k=xe(e,t+12),W=xe(e,t+14),_=i[0]+(v&8191),F=i[1]+((v>>>13|w<<3)&8191),P=i[2]+((w>>>10|T<<6)&8191),N=i[3]+((T>>>7|O<<9)&8191),h=i[4]+((O>>>4|K<<12)&8191),x=i[5]+(K>>>1&8191),S=i[6]+((K>>>14|A<<2)&8191),M=i[7]+((A>>>11|k<<5)&8191),H=i[8]+((k>>>8|W<<8)&8191),D=i[9]+(W>>>5|s),B=0,U=B+_*a+F*(5*b)+P*(5*m)+N*(5*p)+h*(5*g);B=U>>>13,U&=8191,U+=x*(5*f)+S*(5*d)+M*(5*u)+H*(5*c)+D*(5*l),B+=U>>>13,U&=8191;let C=B+_*l+F*a+P*(5*b)+N*(5*m)+h*(5*p);B=C>>>13,C&=8191,C+=x*(5*g)+S*(5*f)+M*(5*d)+H*(5*u)+D*(5*c),B+=C>>>13,C&=8191;let z=B+_*c+F*l+P*a+N*(5*b)+h*(5*m);B=z>>>13,z&=8191,z+=x*(5*p)+S*(5*g)+M*(5*f)+H*(5*d)+D*(5*u),B+=z>>>13,z&=8191;let ee=B+_*u+F*c+P*l+N*a+h*(5*b);B=ee>>>13,ee&=8191,ee+=x*(5*m)+S*(5*p)+M*(5*g)+H*(5*f)+D*(5*d),B+=ee>>>13,ee&=8191;let te=B+_*d+F*u+P*c+N*l+h*a;B=te>>>13,te&=8191,te+=x*(5*b)+S*(5*m)+M*(5*p)+H*(5*g)+D*(5*f),B+=te>>>13,te&=8191;let $=B+_*f+F*d+P*u+N*c+h*l;B=$>>>13,$&=8191,$+=x*a+S*(5*b)+M*(5*m)+H*(5*p)+D*(5*g),B+=$>>>13,$&=8191;let ne=B+_*g+F*f+P*d+N*u+h*c;B=ne>>>13,ne&=8191,ne+=x*l+S*a+M*(5*b)+H*(5*m)+D*(5*p),B+=ne>>>13,ne&=8191;let ue=B+_*p+F*g+P*f+N*d+h*u;B=ue>>>13,ue&=8191,ue+=x*c+S*l+M*a+H*(5*b)+D*(5*m),B+=ue>>>13,ue&=8191;let Z=B+_*m+F*p+P*g+N*f+h*d;B=Z>>>13,Z&=8191,Z+=x*u+S*c+M*l+H*a+D*(5*b),B+=Z>>>13,Z&=8191;let oe=B+_*b+F*m+P*p+N*g+h*f;B=oe>>>13,oe&=8191,oe+=x*d+S*u+M*c+H*l+D*a,B+=oe>>>13,oe&=8191,B=(B<<2)+B|0,B=B+U|0,U=B&8191,B=B>>>13,C+=B,i[0]=U,i[1]=C,i[2]=z,i[3]=ee,i[4]=te,i[5]=$,i[6]=ne,i[7]=ue,i[8]=Z,i[9]=oe}finalize(){let{h:e,pad:t}=this,r=new Uint16Array(10),s=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=s,s=e[a]>>>13,e[a]&=8191;e[0]+=s*5,s=e[0]>>>13,e[0]&=8191,e[1]+=s,s=e[1]>>>13,e[1]&=8191,e[2]+=s,r[0]=e[0]+5,s=r[0]>>>13,r[0]&=8191;for(let a=1;a<10;a++)r[a]=e[a]+s,s=r[a]>>>13,r[a]&=8191;r[9]-=8192;let i=(s^1)-1;for(let a=0;a<10;a++)r[a]&=i;i=~i;for(let a=0;a<10;a++)e[a]=e[a]&i|r[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let o=e[0]+t[0];e[0]=o&65535;for(let a=1;a<8;a++)o=(e[a]+t[a]|0)+(o>>>16)|0,e[a]=o&65535;Qe(r)}update(e){Sn(this),we(e),e=Lt(e);let{buffer:t,blockLen:r}=this,s=e.length;for(let i=0;i>>0,e[i++]=r[o]>>>8;return e}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}};function Wo(n){let e=(r,s)=>n(s).update(r).digest(),t=n(new Uint8Array(32));return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=r=>n(r),e}var Qs=Wo(n=>new Bn(n));function ri(n,e,t,r,s,i=20){let o=n[0],a=n[1],l=n[2],c=n[3],u=e[0],d=e[1],f=e[2],g=e[3],p=e[4],m=e[5],b=e[6],v=e[7],w=s,T=t[0],O=t[1],K=t[2],A=o,k=a,W=l,_=c,F=u,P=d,N=f,h=g,x=p,S=m,M=b,H=v,D=w,B=T,U=O,C=K;for(let ee=0;ee{n.update(e);let t=e.length%16;t&&n.update($o.subarray(t))},Go=new Uint8Array(32);function ti(n,e,t,r,s){s!==void 0&&we(s,void 0,"AAD");let i=n(e,t,Go),o=Ys(r.length,s?s.length:0,!0),a=Qs.create(i);s&&ei(a,s),ei(a,r),a.update(o);let l=a.digest();return Qe(i,o),l}var ni=n=>(e,t,r)=>({encrypt(i,o){let a=i.length;o=An(a+16,o,!1),o.set(i);let l=o.subarray(0,-16);n(e,t,l,l,1);let c=ti(n,e,t,l,r);return o.set(c,a),Qe(c),o},decrypt(i,o){o=An(i.length-16,o,!1);let a=i.subarray(0,-16),l=i.subarray(-16),c=ti(n,e,t,a,r);if(!Er(l,c))throw new Error("invalid tag");return o.set(i.subarray(0,-16)),n(e,t,o,o,1),Qe(c),o}}),Mc=En({blockSize:64,nonceLength:12,tagLength:16},ni(kr)),Bc=En({blockSize:64,nonceLength:24,tagLength:16},ni(Vo));function ii(n,e,t){return pt(n),t===void 0&&(t=new Uint8Array(n.outputLen)),st(n,t,e)}var Rn=Uint8Array.of(0),si=Uint8Array.of();function oi(n,e,t,r=32){pt(n),Pe(r,"length");let s=n.outputLen;if(r>255*s)throw new Error("Length must be <= 255*HashLen");let i=Math.ceil(r/s);t===void 0?t=si:ae(t,void 0,"info");let o=new Uint8Array(i*s),a=st.create(n,e),l=a._cloneInto(),c=new Uint8Array(a.outputLen);for(let u=0;utypeof t=="string"):e.every(t=>Number.isSafeInteger(t)):!1}function Xt(n,e){if(typeof e!="string")throw new Error(`${n}: string expected`);return!0}function _n(n){if(!Number.isSafeInteger(n))throw new Error(`invalid integer: ${n}`)}function Ln(n){if(!Array.isArray(n))throw new Error("array expected")}function Mr(n,e){if(!ci(!0,e))throw new Error(`${n}: array of strings expected`)}function Zo(n,e){if(!ci(!1,e))throw new Error(`${n}: array of numbers expected`)}function Xo(...n){let e=i=>i,t=(i,o)=>a=>i(o(a)),r=n.map(i=>i.encode).reduceRight(t,e),s=n.map(i=>i.decode).reduce(t,e);return{encode:r,decode:s}}function Jo(n){let e=typeof n=="string"?n.split(""):n,t=e.length;Mr("alphabet",e);let r=new Map(e.map((s,i)=>[s,i]));return{encode:s=>(Ln(s),s.map(i=>{if(!Number.isSafeInteger(i)||i<0||i>=t)throw new Error(`alphabet.encode: digit index outside alphabet "${i}". Allowed: ${n}`);return e[i]})),decode:s=>(Ln(s),s.map(i=>{Xt("alphabet.decode",i);let o=r.get(i);if(o===void 0)throw new Error(`Unknown letter: "${i}". Allowed: ${n}`);return o}))}}function Qo(n=""){return Xt("join",n),{encode:e=>(Mr("join.decode",e),e.join(n)),decode:e=>(Xt("join.decode",e),e.split(n))}}function ea(n,e="="){return _n(n),Xt("padding",e),{encode(t){for(Mr("padding.encode",t);t.length*n%8;)t.push(e);return t},decode(t){Mr("padding.decode",t);let r=t.length;if(r*n%8)throw new Error("padding: invalid, string should have whole number of bytes");for(;r>0&&t[r-1]===e;r--)if((r-1)*n%8===0)throw new Error("padding: invalid, string has too much padding");return t.slice(0,r)}}}var hi=(n,e)=>e===0?n:hi(e,n%e),Br=(n,e)=>n+(e-hi(n,e)),Tn=(()=>{let n=[];for(let e=0;e<40;e++)n.push(2**e);return n})();function ai(n,e,t,r){if(Ln(n),e<=0||e>32)throw new Error(`convertRadix2: wrong from=${e}`);if(t<=0||t>32)throw new Error(`convertRadix2: wrong to=${t}`);if(Br(e,t)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${t} carryBits=${Br(e,t)}`);let s=0,i=0,o=Tn[e],a=Tn[t]-1,l=[];for(let c of n){if(_n(c),c>=o)throw new Error(`convertRadix2: invalid data word=${c} from=${e}`);if(s=s<32)throw new Error(`convertRadix2: carry overflow pos=${i} from=${e}`);for(i+=e;i>=t;i-=t)l.push((s>>i-t&a)>>>0);let u=Tn[i];if(u===void 0)throw new Error("invalid carry");s&=u-1}if(s=s<=e)throw new Error("Excess padding");if(!r&&s>0)throw new Error(`Non-zero padding: ${s}`);return r&&i>0&&l.push(s>>>0),l}function ta(n,e=!1){if(_n(n),n<=0||n>32)throw new Error("radix2: bits should be in (0..32]");if(Br(8,n)>32||Br(n,8)>32)throw new Error("radix2: carry overflow");return{encode:t=>{if(!li(t))throw new Error("radix2.encode input should be Uint8Array");return ai(Array.from(t),8,n,!e)},decode:t=>(Zo("radix2.decode",t),Uint8Array.from(ai(t,n,8,e)))}}var ra=typeof Uint8Array.from([]).toBase64=="function"&&typeof Uint8Array.fromBase64=="function",na=(n,e)=>{Xt("base64",n);let t=e?/^[A-Za-z0-9=_-]+$/:/^[A-Za-z0-9=+/]+$/,r=e?"base64url":"base64";if(n.length>0&&!t.test(n))throw new Error("invalid base64");return Uint8Array.fromBase64(n,{alphabet:r,lastChunkHandling:"strict"})},On=ra?{encode(n){return Yo(n),n.toBase64()},decode(n){return na(n,!1)}}:Xo(ta(6),Jo("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),ea(6),Qo(""));var sa=new TextDecoder("utf-8"),ui=new TextEncoder,In=1,Cn=4294967295,Nn=65536;function ia(n,e){let t=qs.getSharedSecret(n,Te("02"+e)).subarray(1,33);return ii(qe,t,ui.encode("nip44-v2"))}function di(n,e){let t=oi(qe,n,e,76);return{chacha_key:t.subarray(0,32),chacha_nonce:t.subarray(32,44),hmac_key:t.subarray(44,76)}}function Pn(n){if(!Number.isSafeInteger(n)||n<1)throw new Error("expected positive integer");if(n<=32)return 32;let e=2**(Math.floor(Math.log2(n-1))+1),t=e<=256?32:e/8;return t*(Math.floor((n-1)/t)+1)}function oa(n){if(!Number.isSafeInteger(n)||n65535)throw new Error("invalid plaintext size: must be between 1 and 65535 bytes");let e=new Uint8Array(2);return new DataView(e.buffer).setUint16(0,n,!1),e}function aa(n){if(!Number.isSafeInteger(n)||nCn)throw new Error("invalid plaintext size: must be between 65536 and 4294967295 bytes");let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,n,!1),e}function fi(n){let e=ui.encode(n),t=e.length;if(tCn)throw new Error("invalid plaintext size: must be between 1 and 4294967295 bytes");let r=t>=Nn?be(new Uint8Array([0,0]),aa(t)):oa(t),s=new Uint8Array(Pn(t)-t);return be(r,e,s)}function pi(n){let e=new DataView(n.buffer,n.byteOffset,n.byteLength),t=e.getUint16(0),r,s;if(t===0){if(r=e.getUint32(2),rCn||i.length!==r||n.length!==s+Pn(r))throw new Error("invalid padding");return sa.decode(i)}function gi(n,e,t){if(t.length!==32)throw new Error("AAD associated data must be 32 bytes");let r=be(t,e);return st(qe,n,r)}function la(n){if(typeof n!="string")throw new Error("payload must be a valid string");let e=n.length;if(e<132)throw new Error("invalid payload length: "+e);if(n[0]==="#")throw new Error("unknown encryption version");let t;try{t=On.decode(n)}catch(i){throw new Error("invalid base64: "+i.message)}let r=t.length;if(r<99)throw new Error("invalid data length: "+r);let s=t[0];if(s!==2)throw new Error("unknown encryption version "+s);return{nonce:t.subarray(1,33),ciphertext:t.subarray(33,-32),mac:t.subarray(-32)}}function ca(n,e,t=Ye(32)){let{chacha_key:r,chacha_nonce:s,hmac_key:i}=di(e,t),o=fi(n),a=kr(r,s,o),l=gi(i,a,t);return On.encode(be(new Uint8Array([2]),t,a,l))}function ha(n,e){let{nonce:t,ciphertext:r,mac:s}=la(n),{chacha_key:i,chacha_nonce:o,hmac_key:a}=di(e,t),l=gi(a,r,t);if(!Er(l,s))throw new Error("invalid MAC");let c=kr(i,o,r);return pi(c)}var Rr={utils:{getConversationKey:ia,calcPaddedLen:Pn,pad:fi,unpad:pi},encrypt:ca,decrypt:ha};function Jt(n,e){if(n.ids&&n.ids.indexOf(e.id)===-1||n.kinds&&n.kinds.indexOf(e.kind)===-1||n.authors&&n.authors.indexOf(e.pubkey)===-1)return!1;for(let t in n)if(t[0]==="#"){let r=t.slice(1),s=n[`#${r}`];if(s&&!e.tags.find(([i,o])=>i===t.slice(1)&&s.indexOf(o)!==-1))return!1}return!(n.since&&e.created_atn.until)}var Tr=3,Lr=24170,Hn=24171,_r="x",Qt=/^[0-9a-f]{64}$/u,ua=/^[a-z0-9](?:[a-z0-9-]{0,31})$/u,da=1*1024*1024,mi=16*1024,fa=64*1024,yi=8*1024,pa=2*1024,bi=30,ga=64,ma=256,wi=new TextEncoder;function bt(n){return typeof n=="string"?wi.encode(n).byteLength:n instanceof ArrayBuffer||ArrayBuffer.isView(n)?n.byteLength:wi.encode(String(n)).byteLength}function ya(n){return Array.from(globalThis.crypto.getRandomValues(new Uint8Array(n)),e=>e.toString(16).padStart(2,"0")).join("")}function Ai(n,e){return Array.isArray(n?.tags)?n.tags.filter(t=>Array.isArray(t)&&t.length>=2&&t[0]===e&&typeof t[1]=="string").map(t=>t[1]):[]}var Dn=n=>Math.min(Number.MAX_SAFE_INTEGER,n);function vi(n,e){let t=Ai(n,e);return t.length===1?t[0]:null}function xi(n){let e=JSON.parse(n);if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Expected a JSON object.");return e}function ot(n){return typeof n=="string"&&ua.test(n)}function Si(n){return typeof n=="string"&&n.length>=8&&n.length<=64&&/^[a-zA-Z0-9_-]+$/u.test(n)}function ba(n){let e=new URL(String(n)),t=e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname==="[::1]";if(e.protocol!=="wss:"&&!(e.protocol==="ws:"&&t))throw new Error("Relay URLs must use wss://, except for loopback tests.");return e.username="",e.password="",e.hash="",e.toString()}var Or=class{constructor(e,{label:t="relay",WebSocketImpl:r=globalThis.WebSocket,connectTimeoutMs:s=8e3,reconnect:i=!1,reconnectMaxMs:o=3e4,readyOnFirstRelay:a=!1}={}){if(!Array.isArray(e)||e.length<1||e.length>8)throw new Error("RelayPool requires between one and eight relay URLs.");if(typeof r!="function")throw new Error("RelayPool requires a WebSocket implementation.");this.urls=[...new Set(e.map(ba))],this.label=t,this.WebSocketImpl=r,this.connectTimeoutMs=s,this.sockets=[],this.handlers=new Set,this.relayOpenHandlers=new Set,this.seen=new Set,this.connected=!1,this.closed=!1,this.connecting=null,this.pendingSockets=new Map,this.readyWaiters=new Set,this.reconnect=i,this.readyOnFirstRelay=a===!0,this.reconnectMaxMs=o,this.subscriptions=new Map,this.retryTimers=new Set,this.published=0,this.rejected=0,this.rejectedTimestamp=0,this.sinceDropped=0,this.rejectHandlers=new Set}async connect(){if(this.closed)throw new Error("RelayPool is closed.");if(!(this.connected&&this.sockets.length))return this.connecting?this.connecting:(this.connecting=this.#r().finally(()=>{this.connecting=null}),this.connecting)}async#r(){this.connected=!0;let e,t=this.reconnect||this.readyOnFirstRelay?new Promise((o,a)=>this.readyWaiters.add(e={resolve:o,reject:a})):null,r=Promise.allSettled(this.urls.map(o=>this.#t(o))),s=o=>{let a=o.map(l=>l.status==="rejected"?l.reason?.message:"").filter(Boolean);return new Error(`No relay reachable${a.length?`: ${a.join("; ")}`:"."}`)};if(this.reconnect){r.then(o=>{this.closed||o.forEach((a,l)=>{a.status==="rejected"&&this.#e(this.urls[l],1)})}).catch(o=>e.reject(o));try{if(await t,this.closed)throw new Error("RelayPool is closed.")}finally{this.readyWaiters.delete(e)}return}if(t){r.then(o=>{this.sockets.length===0&&e.reject(s(o))});try{if(await t,this.closed)throw new Error("RelayPool is closed.")}finally{this.readyWaiters.delete(e)}return}let i=await r;if(this.closed)throw new Error("RelayPool is closed.");if(this.sockets.length===0)throw s(i);this.connected=!0}#t(e){return new Promise((t,r)=>{let s=!1,i=new this.WebSocketImpl(e),o=l=>{if(!s)if(s=!0,clearTimeout(a),this.pendingSockets.delete(i),l){try{i.close()}catch{}r(l)}else t(i)},a=setTimeout(()=>{o(new Error(`${e} timed out`))},this.connectTimeoutMs);this.pendingSockets.set(i,()=>o(new Error("RelayPool is closed."))),i.addEventListener("open",()=>{if(s||this.closed){try{i.close()}catch{}return}this.sockets.push(i);for(let[c,u]of this.subscriptions)i.send(JSON.stringify(["REQ",c,u]));o();for(let c of this.readyWaiters)c.resolve();this.readyWaiters.clear();let l=c=>{if(this.closed||!this.sockets.includes(i))return!1;try{return i.send(JSON.stringify(["EVENT",c])),this.published+=1,!0}catch{return!1}};for(let c of[...this.relayOpenHandlers])try{c(l)}catch{}}),i.addEventListener("error",()=>o(new Error(`${e} failed to connect`))),i.addEventListener("message",l=>this.#s(l.data)),i.addEventListener("close",()=>{let l=this.sockets.includes(i);this.sockets=this.sockets.filter(c=>c!==i),o(new Error(`${e} closed`)),this.reconnect&&this.connected&&l&&this.#e(e,1)})})}#e(e,t){if(this.closed)return;let r=Math.min(this.reconnectMaxMs,1e3*2**Math.min(t,5))*(.5+Math.random()*.5),s=setTimeout(()=>{this.retryTimers.delete(s),this.connected&&this.#t(e).catch(()=>{this.connected&&!this.sockets.some(i=>i.url===e)&&this.#e(e,t+1)})},r);this.retryTimers.add(s)}#s(e){if(this.closed||bt(e)>da)return;let t;try{t=JSON.parse(String(e))}catch{return}if(Array.isArray(t)&&t[0]==="OK"&&t[2]===!1){this.rejected+=1,/created_at|timestamp|future|too (old|far|new)/i.test(String(t[3]||""))&&(this.rejectedTimestamp=Math.min(Number.MAX_SAFE_INTEGER,this.rejectedTimestamp+1));for(let i of this.rejectHandlers)try{i({id:t[1],message:String(t[3]||"")})}catch{}return}if(!Array.isArray(t)||t[0]!=="EVENT"||!t[2]||typeof t[2]!="object")return;let r=t[2],s=this.subscriptions.get(t[1]);try{s&&!Jt(s,r)&&s.since&&Number.isSafeInteger(r.created_at)&&r.created_at1e4&&this.seen.delete(this.seen.values().next().value);for(let i of this.handlers)i(r)}subscribe(e){if(!this.connected||this.sockets.length===0)throw new Error("RelayPool is not connected.");if(this.subscriptions.size>=32)throw new Error("Relay subscription capacity reached.");let t=ya(8),r=JSON.stringify(["REQ",t,e]);this.subscriptions.set(t,e);for(let s of this.sockets)s.send(r);return t}unsubscribe(e){if(this.subscriptions.delete(e))for(let t of this.sockets)try{t.send(JSON.stringify(["CLOSE",e]))}catch{}}onReject(e){return this.rejectHandlers.add(e),()=>this.rejectHandlers.delete(e)}onEvent(e){return this.handlers.add(e),()=>this.handlers.delete(e)}onRelayOpen(e){return this.relayOpenHandlers.add(e),()=>this.relayOpenHandlers.delete(e)}publish(e){if(!this.connected||this.sockets.length===0)throw new Error("RelayPool has no connected relay.");let t=JSON.stringify(["EVENT",e]);for(let r of this.sockets)r.send(t);this.published+=1}close(){this.closed=!0,this.connected=!1;for(let e of this.retryTimers)clearTimeout(e);this.retryTimers.clear(),this.subscriptions.clear(),this.rejectHandlers.clear();for(let e of[...this.pendingSockets.values()])e();this.pendingSockets.clear();for(let e of this.readyWaiters)e.reject(new Error("RelayPool is closed."));this.readyWaiters.clear();for(let e of this.sockets)try{e.close()}catch{}this.sockets=[],this.handlers.clear(),this.relayOpenHandlers.clear(),this.seen.clear()}},Ir=class{#r=null;#t=null;#e=new Map;#s=null;constructor({pool:e,swarmId:t,secretKey:r=Yt(),maxEventAgeSeconds:s=120}={}){if(!e)throw new Error("RelaySwarmSession requires a relay pool.");if(typeof t!="string"||t.length<8||t.length>128)throw new Error("Invalid swarm identifier.");this.pool=e,this.swarmId=t,this.secretKey=r,this.pubkey=Vs(r),this.maxEventAgeSeconds=s,this.presenceHandlers=new Set,this.signalHandlers=new Set,this.errorHandlers=new Set,this.started=!1,this.unsubscribe=null,this.subscriptionIds=[],this.clock={aheadRejected:0,staleRejected:0,maxAheadSeconds:0,signalAges:[]}}clockDiagnostics(){let e=[...this.clock.signalAges].sort((t,r)=>t-r);return{aheadRejected:this.clock.aheadRejected,staleRejected:this.clock.staleRejected,maxAheadSeconds:this.clock.maxAheadSeconds,signalSamples:e.length,signalAgeMedianSeconds:e.length?e[Math.floor(e.length/2)]:null}}start(){if(this.started)return;this.started=!0,this.unsubscribe=this.pool.onEvent(t=>this.#i(t));let e={[`#${_r}`]:[this.swarmId],since:Math.floor(Date.now()/1e3)-2};try{this.#t=this.pool.onRelayOpen?.(t=>{if(!this.started||!this.#r)return;let r=Math.floor(Date.now()/1e3)-this.#r.created_at;if(!Number.isFinite(r)||!Number.isFinite(this.maxEventAgeSeconds)||r<-bi||r>this.maxEventAgeSeconds){this.#r=null;return}t(this.#r)}),this.subscriptionId=this.pool.subscribe({...e,since:Math.floor(Date.now()/1e3)-this.maxEventAgeSeconds,kinds:[Lr]}),this.subscriptionIds.push(this.subscriptionId),this.subscriptionIds.push(this.pool.subscribe({...e,kinds:[Hn],"#p":[this.pubkey]}))}catch(t){for(let r of this.subscriptionIds)this.pool.unsubscribe?.(r);throw this.subscriptionIds=[],this.unsubscribe?.(),this.unsubscribe=null,this.started=!1,this.#t?.(),this.#t=null,this.#r=null,t}}onPresence(e){return this.presenceHandlers.add(e),()=>this.presenceHandlers.delete(e)}onSignal(e){return this.signalHandlers.add(e),()=>this.signalHandlers.delete(e)}onError(e){return this.errorHandlers.add(e),()=>this.errorHandlers.delete(e)}announcePresence({role:e,transports:t=[],have:r=[],open:s,ticket:i}={}){if(i!==void 0&&!ye(i))throw new Error("Invalid presence ticket.");if(!ot(e))throw new Error("Invalid presence role.");if(!Array.isArray(t)||t.length>8)throw new Error("Invalid transport capability list.");if(!Array.isArray(r)||r.length>32||r.some(c=>!Qt.test(c)))throw new Error("Invalid object hash list.");let o=t.map(c=>{if(!c||typeof c!="object"||!ot(c.type)||!Qt.test(c.publicKey)||c.obj!==void 0&&!Ei(c.obj))throw new Error("Invalid transport capability.");return{type:c.type,publicKey:c.publicKey,...c.obj===void 0?{}:{obj:c.obj}}}),a=JSON.stringify({v:Tr,role:e,transports:o,have:[...new Set(r)],...s===void 0?{}:{open:!!s},...i===void 0?{}:{ticket:i}});if(bt(a)>mi)throw new Error("Presence payload is too large.");let l=vr({kind:Lr,created_at:Math.floor(Date.now()/1e3),tags:[[_r,this.swarmId]],content:a},this.secretKey);return this.pool.publish(l),this.#r=JSON.parse(JSON.stringify(l)),l}sendSignal(e,{type:t,transport:r,requestId:s,payload:i={}}={}){if(!Qt.test(e))throw new Error("Invalid signal recipient.");if(!ot(t)||!ot(r)||!Si(s))throw new Error("Invalid signal envelope.");if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Invalid signal payload.");let o=JSON.stringify({v:Tr,type:t,transport:r,requestId:s,payload:i});if(bt(o)>yi)throw new Error("Signal payload is too large.");let a=Rr.encrypt(o,this.#n(e)),l=vr({kind:Hn,created_at:Math.floor(Date.now()/1e3),tags:[[_r,this.swarmId],["p",e]],content:a},this.secretKey);return this.pool.publish(l),l}waitForPresence(e,t=15e3){return this.#d(this.presenceHandlers,e,t,"Timed out waiting for RelaySwarm presence.")}waitForSignal(e,t=15e3){return this.#d(this.signalHandlers,e,t,"Timed out waiting for RelaySwarm signal.")}#d(e,t,r,s){return new Promise((i,o)=>{let a=c=>{let u=!1;try{u=t(c)}catch(d){clearTimeout(l),e.delete(a),o(d);return}u&&(clearTimeout(l),e.delete(a),i(c))},l=setTimeout(()=>{e.delete(a),o(new Error(s))},r);e.add(a)})}#i(e){if(e.pubkey===this.pubkey||e.kind!==Lr&&e.kind!==Hn||!Number.isSafeInteger(e.created_at)||vi(e,_r)!==this.swarmId)return;let t=Math.floor(Date.now()/1e3)-e.created_at;if(t<-bi){this.clock.aheadRejected=Dn(this.clock.aheadRejected+1),this.clock.maxAheadSeconds=Math.max(this.clock.maxAheadSeconds,Dn(-t));return}if(t>this.maxEventAgeSeconds){this.clock.staleRejected=Dn(this.clock.staleRejected+1);return}try{e.kind===Lr?this.#c(e):this.#o(e)}catch{}}#c(e){if(bt(e.content)>mi||Ai(e,"p").length!==0)return;let t=xi(e.content);if(t.v!==Tr||!ot(t.role)||!Array.isArray(t.transports)||t.transports.length>8||!Array.isArray(t.have)||t.have.length>32||t.have.some(o=>!Qt.test(o)))return;let r=t.transports.map(o=>{if(!o||typeof o!="object"||!ot(o.type)||!Qt.test(o.publicKey))throw new Error("Invalid transport capability.");return{type:o.type,publicKey:o.publicKey,...Ei(o.obj)?{obj:o.obj}:{}}}),s=typeof t.open=="boolean"?t.open:null,i=ye(t.ticket)?t.ticket:null;this.#h(this.presenceHandlers,{from:e.pubkey,event:e,payload:{...t,transports:r,open:s,ticket:i}})}#o(e){if(bt(e.content)>fa||vi(e,"p")!==this.pubkey)return;let t=Rr.decrypt(e.content,this.#n(e.pubkey));if(bt(t)>yi)return;let r=xi(t);r.v!==Tr||!ot(r.type)||!ot(r.transport)||!Si(r.requestId)||!r.payload||typeof r.payload!="object"||Array.isArray(r.payload)||(this.clock.signalAges.length>=ga&&this.clock.signalAges.shift(),this.clock.signalAges.push(Math.floor(Date.now()/1e3)-e.created_at),this.#h(this.signalHandlers,{from:e.pubkey,event:e,payload:r}))}#n(e){this.#s!==this.secretKey&&(this.#e.clear(),this.#s=this.secretKey);let t=this.#e.get(e);return t?this.#e.delete(e):(t=Rr.utils.getConversationKey(this.secretKey,e),this.#e.size>=ma&&this.#e.delete(this.#e.keys().next().value)),this.#e.set(e,t),t}#h(e,t){for(let r of e)Promise.resolve().then(()=>r(t)).catch(s=>{for(let i of this.errorHandlers)i(s)})}close(){this.unsubscribe?.(),this.#t?.(),this.#t=null,this.#r=null,this.#e.clear(),this.#s=null;for(let e of this.subscriptionIds)this.pool.unsubscribe?.(e);this.subscriptionIds=[],this.unsubscribe=null,this.started=!1,this.presenceHandlers.clear(),this.signalHandlers.clear(),this.errorHandlers.clear()}};function Ei(n){return Number.isSafeInteger(n)&&n>=1&&n<=15}function ye(n){return typeof n=="string"&&n.length>0&&bt(n)<=pa}var Un=/^[0-9a-f]{64}$/u,ki="relayswarm-abandon";var Mi=new Set(["host","host-stop","admission","rotation","integrity","request-timeout","request-abort","native-failed","native-closed","native-disconnected","channel-close","channel-error","protocol","send-error","serve-error","upload-queue","upload-drain-timeout"]),at=class{static ABANDON_REASON=ki;#r=!1;constructor({pubkey:e,pc:t,channel:r,maxSegmentBytes:s,onRequest:i,onHaveChange:o,onScheduleChange:a,onClose:l,onUploadCancelled:c,maxQueuedRequests:u=4,drainTimeoutMs:d=3e3}){this.pubkey=e,this.pc=t,this.channel=r,this.maxSegmentBytes=s,this.onRequest=i,this.onHaveChange=o,this.onScheduleChange=a,this.contribution={serving:!1,rendition:null,at:0},this.fetching=new Map,this.renditions=new Map,this.announced=new Map,this.onClose=l,this.onUploadCancelled=c,this.maxQueuedRequests=u,this.drainTimeoutMs=d,this.maxChunks=Math.max(1,Math.ceil(s/16384)*4),this.have=new Set,this.pending=null,this.nextId=1,this.serving=Promise.resolve(),this.closed=!1,this.openedAt=Date.now(),this.lastServedAt=0,this.lastDeliveredAt=0,this.outboundInFlight=0,this.uploads=new Set,this.bytesIn=0,this.bytesOut=0,r.binaryType="arraybuffer",r.bufferedAmountLowThreshold=32768,r.addEventListener("message",f=>{try{this.#e(f.data)}catch{this.close("protocol")}}),r.addEventListener("close",()=>this.close("channel-close")),r.addEventListener("error",()=>this.close("channel-error")),t.addEventListener("connectionstatechange",()=>{let f=t.connectionState;["failed","closed","disconnected"].includes(f)&&this.close(`native-${f}`)})}get busy(){return this.pending!==null}get transferring(){return this.pending!==null||this.outboundInFlight>0}get lastUsefulAt(){return Math.max(this.lastDeliveredAt,this.lastServedAt,this.openedAt)}sendHave(e){this.#t({t:"have",keys:e.slice(-256)})}sendHaveChange(e=[],t=[]){(e.length||t.length)&&this.#t({t:"have",add:e,del:t})}sendContribution(e,t){this.#t({t:"contribution",serving:e,rendition:t})}sendFetching(e,t=0){this.#t({t:"fetching",k:e,ms:t})}request(e,t,{signal:r,expectedSize:s,onResult:i,onProgress:o}={}){let a=null;try{a=performance.now()}catch{}let l=!1,c=(u,d=null)=>{if(!l&&(l=!0,typeof i=="function"))try{let f=null;if(Number.isFinite(a))try{f=performance.now()-a}catch{}let g=d?.received??0,p=Number.isFinite(d?.firstByteAt)&&Number.isFinite(a)?d.firstByteAt-a:null;i({outcome:u,elapsedMs:Number.isFinite(f)&&f>=0?f:null,timeoutMs:Number.isFinite(t)&&t>=0?t:null,expectedBytes:Number.isSafeInteger(s)&&s>=0?s:null,receivedBytes:Number.isSafeInteger(g)&&g>=0?g:null,firstByteMs:Number.isFinite(p)&&p>=0?p:null,metadataReceived:d?d.size>=0:!1,draining:d?.draining===!0,closeReason:Mi.has(this.closeReason)?this.closeReason:null})}catch{}};if(this.closed||this.pending||r?.aborted){let u=Promise.resolve(null);return c(this.closed?"closed":this.pending?"busy":"abort"),u}return new Promise(u=>{let d=this.nextId++,f=w=>{clearTimeout(this.pending.timer),r?.removeEventListener("abort",m),u(w)},g=(w,T=w?"payload":"none",O=!0)=>{if(this.pending?.id!==d)return;let K=this.pending,A=K.draining;f(w),this.pending=null,w&&(this.lastDeliveredAt=Date.now()),A&&!this.closed&&this.onScheduleChange?.(this),O&&c(T,K)},p=w=>{let T=this.pending;if(!T||T.id!==d||T.draining)return;let O=!1;try{O=this.channel.ordered===!0&&this.channel.maxRetransmits===null&&this.channel.maxPacketLifeTime===null&&this.channel.readyState==="open"}catch{}let K=w!=="request-abort"?"timeout":r?.reason===ki?"abandoned":"abort";if(!O){g(null,K,!1);try{this.close(w)}finally{c(K,T)}return}T.draining=!0,T.parts.length=0,f(null),T.timer=setTimeout(()=>{this.pending===T&&T.draining&&this.close(w)},this.drainTimeoutMs),c(K,T),T.cancelled=this.#t({t:"cancel",id:d})},m=()=>p("request-abort"),b=()=>p("request-timeout"),v=typeof o=="function"?w=>{try{o(w.received,w.size,Number.isFinite(a)?w.firstByteAt-a:null)}catch{}}:null;this.pending={id:d,key:e,expectedSize:s,size:-1,parts:[],chunks:0,received:0,firstByteAt:null,progress:v,draining:!1,cancelled:!1,finish:g,timer:setTimeout(b,Math.max(1,t))},r?.addEventListener("abort",m,{once:!0}),this.#t({t:"want",id:d,k:e})||g(null,"send-error")})}close(e="host"){if(!this.closed){this.closed=!0,this.closeReason=Mi.has(e)?e:"host",this.fetching.clear(),this.renditions.clear(),this.announced.clear(),this.pending?.finish(null,this.closeReason==="send-error"?"send-error":"closed");try{this.channel.close()}catch{}try{this.pc.close()}catch{}this.onClose?.(this)}}#t(e){if(this.closed||this.channel.readyState!=="open")return!1;try{return this.channel.send(JSON.stringify(e)),!0}catch{return this.close("send-error"),!1}}#e(e){if(this.closed)return;if(typeof e!="string"){let r=this.pending;if(!r)return;if(r.size<0)return this.close("protocol");let s=new Uint8Array(e);if(!s.byteLength||s.byteLength>16384||r.chunks>=this.maxChunks)return this.close("protocol");if(r.chunks+=1,r.received+=s.byteLength,this.bytesIn+=s.byteLength,r.received>r.size)return this.close("protocol");if(r.draining)return;if(r.firstByteAt===null)try{r.firstByteAt=performance.now()}catch{}r.parts.push(s),r.progress?.(r);return}if(e.length>64*1024)return this.close("protocol");let t=JSON.parse(e);if(!(!t||typeof t!="object"))switch(t.t){case"contribution":{if(typeof t.serving!="boolean"||t.rendition!==null&&(typeof t.rendition!="string"||t.rendition.length>2048))return;if(this.contribution={serving:t.serving,rendition:t.rendition,at:Date.now()},t.rendition!==null&&(this.announced.delete(t.rendition),this.announced.size>=8&&this.announced.delete(this.announced.keys().next().value),this.announced.set(t.rendition,Date.now())),!t.serving)this.fetching.clear(),this.renditions.clear();else if(t.rendition!==null){for(let[r,s]of this.renditions)s2e3)return;for(let[r,s]of this.fetching)s<=Date.now()&&this.fetching.delete(r);t.ms===0?this.fetching.delete(t.k):this.contribution.serving&&(this.fetching.has(t.k)||this.fetching.size<24)&&this.fetching.set(t.k,Date.now()+t.ms),this.onScheduleChange?.(this);return}case"have":return this.#s(t);case"want":return this.#d(t);case"cancel":{if(!Number.isSafeInteger(t.id))return;for(let r of this.uploads)r.id===t.id&&(r.cancelled=!0,r.resume?.());return}case"meta":{let r=this.pending;if(!r)return;if(t.id!==r.id)return r.draining?this.close("protocol"):void 0;if(r.size!==-1)return this.close("protocol");if(r.expectedSize!==void 0&&t.size!==r.expectedSize)return this.close("protocol");if(!Number.isSafeInteger(t.size)||t.size<1||t.size>this.maxSegmentBytes)return this.close("protocol");r.size=t.size;return}case"eof":{let r=this.pending;if(!r)return;if(t.id!==r.id)return r.draining?this.close("protocol"):void 0;if(r.cancelled&&r.size>=0)return r.finish(null);if(r.received!==r.size)return this.close("protocol");if(r.draining)return r.finish(null);let s=new Uint8Array(r.size),i=0;for(let o of r.parts)s.set(o,i),i+=o.byteLength;return r.finish(s)}case"none":if(this.pending){if(t.id!==this.pending.id)return this.pending.draining?this.close("protocol"):void 0;if(this.pending.size!==-1)return this.close("protocol");this.pending.finish(null)}return;default:return}}#s(e){let t=s=>Array.isArray(s)?s.filter(i=>typeof i=="string"&&Un.test(i)).slice(0,256):[],r=[];if(Array.isArray(e.keys)){this.have.clear();for(let s of t(e.keys))this.have.add(s);r.push(...this.have)}for(let s of t(e.add)){if(this.have.size>=256)break;this.have.add(s),r.push(s)}for(let s of t(e.del))this.have.delete(s);r.length&&this.onHaveChange?.(this,r)}#d(e){if(!Number.isSafeInteger(e.id)||typeof e.k!="string"||!Un.test(e.k))return;if(this.outboundInFlight>=this.maxQueuedRequests)return this.close("upload-queue");this.outboundInFlight+=1;let t={id:e.id,cancelled:!1};this.uploads.add(t),this.serving=this.serving.then(()=>this.#i(t,e.k)).catch(()=>this.close(this.#r?"upload-drain-timeout":"serve-error")).finally(()=>{this.uploads.delete(t),this.outboundInFlight=Math.max(0,this.outboundInFlight-1)})}async#i(e,t){let{id:r}=e;if(e.cancelled)return this.onUploadCancelled?.(this,0),void this.#t({t:"none",id:r});let s=this.closed?null:await this.onRequest?.(this,t);if(!s)return void this.#t({t:"none",id:r});if(e.cancelled)return this.onUploadCancelled?.(this,s.byteLength),void this.#t({t:"none",id:r});if(!this.#t({t:"meta",id:r,size:s.byteLength}))return;let i=0;for(;i131072&&await this.#c(e),this.closed))return;if(e.cancelled)break;let o=Math.min(i+16384,s.byteLength);this.channel.send(s.subarray(i,o)),i=o}this.bytesOut+=i,this.lastServedAt=Date.now(),i{let s=setTimeout(()=>{i(),this.#r=!0,r(new Error("Peer upload stalled."))},this.drainTimeoutMs),i=()=>{clearTimeout(s),this.channel.removeEventListener("bufferedamountlow",o),this.channel.removeEventListener("close",o),e.resume===o&&delete e.resume},o=()=>{i(),t()};this.channel.addEventListener("bufferedamountlow",o),this.channel.addEventListener("close",o),e.resume=o})}};function Bi(n,e){if(!n.length)return null;let t=[...n].sort((r,s)=>r-s);return t[Math.min(t.length-1,Math.floor(t.length*e))]}var wa=n=>Bi(n,.5),wt=class{constructor(){this.observations=new WeakMap,this.turn=0,this.order=0,this.recentCompletions=[],this.recentFirstBytes=[],this.recentRates=[],this.lastObservedAt=0}observe({firstByteMs:e=null,bytes:t=0,flowMs:r=0,totalFlowMs:s=r}={}){Number.isFinite(e)&&e>=0&&(this.recentFirstBytes.push(Math.min(6e4,e)),this.recentFirstBytes.length>16&&this.recentFirstBytes.shift()),t>=32768&&r>=300&&(this.recentRates.push({rate:Math.min(1e6,t/r),flowMs:Math.max(r,s||0)}),this.recentRates.length>16&&this.recentRates.shift(),this.lastObservedAt=Date.now())}firstByteMs(){return wa(this.recentFirstBytes)}rate(){let e=this.firstByteMs(),t=e===null?[]:this.recentRates.filter(({flowMs:r})=>r>=e*3);return Bi((t.length>=2?t:this.recentRates).map(({rate:r})=>r),.75)}projectMs(e){if(!e)return null;let t=this.firstByteMs(),r=this.rate(),s=[this.minimumMs(e),t!==null&&r?t+e/r:0].filter(Boolean);return s.length?Math.min(...s):null}minimumMs(e){if(!e)return 0;let t=0;for(let{bytes:r,rate:s}of this.recentCompletions)r>=e&&s>t&&(t=s);return t?e/t:0}summary(e){let t=this.observations.get(e);return t?{...t}:{attempts:0,latencyMs:null,throughputBytesPerSecond:null,failureRate:0,consecutiveFailures:0,lastSelected:0}}estimate(e,t){let r=this.summary(e);if(r.latencyMs===null)return null;let s=t&&r.throughputBytesPerSecond?t*1e3/r.throughputBytesPerSecond:0;return Math.max(r.latencyMs,s)}select(e,t,r,s,i=1/0){let o=[...e].filter(p=>!p.closed&&!p.busy&&!r.has(p.pubkey)&&p.have.has(t)&&(this.estimate(p,s)===null||this.estimate(p,s)*1.25+25<=i));if(!o.length)return null;let a=o.filter(p=>!this.observations.get(p)?.attempts),l=o.filter(p=>this.observations.get(p)?.attempts),c=l.filter(p=>this.summary(p).consecutiveFailures===0),u=a.length&&(!c.length||this.turn===0&&i>=100);this.turn=(this.turn+1)%4;let d=u?a:c.length?c:l,f=p=>{let m=this.summary(p);return u?m.lastSelected:(this.estimate(p,s)??1e3)*(1+m.failureRate*4)},g=d.reduce((p,m)=>f(m)a===null?l:a*.75+l*.25,o=Math.min(6e4,Math.max(1,t));s.attempts=Math.min(32,s.attempts+1),s.failureRate=s.failureRate*.75+(r?0:.25),s.consecutiveFailures=r?0:Math.min(32,s.consecutiveFailures+1),r&&(s.latencyMs=i(s.latencyMs,o),s.throughputBytesPerSecond=i(s.throughputBytesPerSecond,Math.min(1e9,r*1e3/o)),this.recentCompletions.push({bytes:r,rate:Math.min(1e6,r/o)}),this.lastObservedAt=Date.now(),this.recentCompletions.length>16&&this.recentCompletions.shift()),this.observations.set(e,s)}};var Cr=class{#r=0;#t=null;#e=-1/0;discard(e){this.#r=0,this.#t=null,Number.isFinite(e)&&(this.#e=Math.max(this.#e,e))}record({freshBytes:e,startAt:t,endAt:r}){if(e===0)return null;if(!Number.isSafeInteger(e)||e<0||!Number.isSafeInteger(this.#r+e)||!Number.isFinite(t)||t<0||!Number.isFinite(r)||rDate.now()){this.clock=e,this.contexts=new Map,this.candidates=new Map,this.window=null,this.counters={checks:0,replacements:0,expired:0,opened:0,verified:0,staleHolder:0,staleBlocked:0,heldMiss:0,rearmed:0,victimUnhelpful:0,victimServing:0,victimConsumer:0,unmetNoHint:0,unmetIneligible:0}}context(e,t){if(!["main","audio"].includes(e))return null;let r=this.contexts.get(e);if(!r||r.rendition!==t)r={mediaType:e,rendition:t,keys:[],lastDemandAt:null,activityAt:this.clock(),spentAt:null,get spent(){return this.spentAt!==null},holders:new Map},this.contexts.set(e,r);else{let s=this.clock();(s=3e4||r.lastDemandAt!==null&&(s=3e4))&&(r.keys=[],r.lastDemandAt=null,r.holders.clear()),r.activityAt=this.clock()}return r}demand(e,t,r){let s=this.context(e,t);if(!s||!er.test(r))return;let i=this.live()&&this.window.context===s?this.window.attempt?.key:null;return s.keys=[...new Set([...i?[i]:[],r,...s.keys])].slice(0,2),s.lastDemandAt=this.clock(),s}hint(e,t,r){!er.test(e)||!Array.isArray(t)||(this.candidates.delete(e),this.candidates.set(e,{pubkey:e,have:[...new Set(t.filter(s=>typeof s=="string"&&er.test(s)))].slice(-8),ticket:ye(r)?r:null,at:this.clock()}),this.candidates.size>64&&this.candidates.delete(this.candidates.keys().next().value))}#r(e){return!!(e&&this.contexts.get(e.mediaType)===e)}holderMiss(e,t,r){if(!this.#r(e)||!er.test(t)||!er.test(r))return!1;let s=e.holders.get(t);return s?s.lastKey===r?!1:(s.misses++,s.lastKey=r,!0):(e.holders.size>=Sa&&e.holders.delete(e.holders.keys().next().value),e.holders.set(t,{firstMissAt:this.clock(),misses:1,lastKey:r}),!0)}holderAhead(e,t){this.holderDelivered(e,t)}holderDelivered(e,t){this.#r(e)&&e.holders.delete(t)}stale(e,t){let r=this.#r(e)?e.holders.get(t):null;return!!r&&r.misses>=va&&this.clock()-r.firstMissAt>=xa}forget(e){for(let t of this.contexts.values())t.holders.delete(e)}spent(e){return e.spentAt!==null}rearm(e,t){if(!this.#r(e)||!this.spent(e))return!1;let r=this.clock();return r=e.activityAt&&t-e.activityAt<3e4&&e.lastDemandAt!==null&&t>=e.lastDemandAt&&t-e.lastDemandAt<3e4}choose(e,t,r){if(this.window?.attempt)return null;let s=this.window?[this.window.context]:[...this.contexts.values()],i=!1,o=!1;for(let a of s){if(!this.current(a)||!t(a)||!r&&this.spent(a)&&!this.window?.vacant)continue;let l=this.hinted(a,e);if(l)return l;this.#t(a)?o||(o=!0,this.counters.unmetIneligible++):i||(i=!0,this.counters.unmetNoHint++)}return null}#t(e){for(let t of this.candidates.values())if(!(this.clock()=6e4)&&e.keys.some(r=>t.have.includes(r)))return!0;return!1}hinted(e,t){for(let r of this.candidates.values()){if(this.clock()=6e4||!t(r))continue;let s=e.keys.find(i=>r.have.includes(i));if(s)return{context:e,candidate:r,key:s}}return null}begin({context:e,candidate:t,key:r}){let s=this.window;if(!s){let o=this.clock();s={context:e,createdAt:o,expiresAt:Math.min(o+15e3,t.at+6e4,e.lastDemandAt+3e4),attempt:null,vacant:!1,victim:null,timer:null},this.window=s}if(s.context!==e||s.attempt||this.clock()>=s.expiresAt)return null;let i={window:s,pubkey:t.pubkey,ticket:t.ticket,key:r,dial:null,negotiation:null};return s.attempt=i,this.counters.checks++,i}valid(e){let t=e?.window,r=this.candidates.get(e?.pubkey);return!!(t&&this.live(t)&&t.attempt===e&&this.current(t.context)&&r&&this.clock()>=r.at&&this.clock()-r.at<6e4&&r.ticket===e.ticket&&r.have.includes(e.key))}replaced(e,t){return!this.valid(e)||this.spent(e.window.context)?!1:(e.window.context.spentAt=this.clock(),e.window.vacant=!0,e.window.victim=t,this.counters.replacements++,!0)}allocated(e,t){e.dial=t,e.window.vacant=!1}abandoned(e){this.window?.attempt===e&&(this.window.attempt=null)}failed(e){let t=this.window?.attempt;!t||t.dial!==e||(t.window.attempt=null,t.window.vacant=t.window.victim!==null)}end(e=this.window){return!e||this.window!==e?!1:(this.window=null,!0)}verified(e){return!e||this.contexts.get(e.mediaType)!==e?!1:(e.spentAt=null,this.counters.verified++,!0)}live(e=this.window){return!!(e&&this.window===e&&this.clock()>=e.createdAt&&this.clock()e+t.keys.length,0),replacementSpent:[...this.contexts.values()].filter(e=>this.spent(e)).length,replacementRearmMs:Ri,opportunityActive:this.live(),remainingMs:this.live()?Math.min(15e3,this.window.expiresAt-this.clock()):0,vacancyReserved:this.reserved(),counters:{...this.counters}}}clear(){this.window=null,this.contexts.clear(),this.candidates.clear()}};function lt(n,e,t){return new Promise((r,s)=>{let i=new AbortController,o=!1,a,l=(u,d,f=!1,g=d)=>{o||(o=!0,clearTimeout(a),e?.removeEventListener("abort",c),f&&i.abort(g),u?r(d):s(d))},c=()=>l(!1,new Error("Operation cancelled."),!0,e.reason);if(e?.aborted)return c();e?.addEventListener("abort",c,{once:!0}),a=setTimeout(()=>l(!1,new Error("Operation cancelled or timed out."),!0),t),Promise.resolve().then(()=>{if(!o)return n(i.signal)}).then(u=>l(!0,u),u=>l(!1,u))})}var Ti=24172,Ea=24173,Aa=24174,zn=/^[0-9a-f]{64}$/u,ka="relayswarm-segment-v1",Ma="relayswarm-segment-v2",Ba="relayswarm-segment-v3",Li={1:ka,2:Ma,3:Ba},Ra=new TextEncoder,Ta=512,vt=new Map;function Nr(n){let e={id:n.id,pubkey:n.pubkey,created_at:n.created_at,kind:n.kind,tags:n.tags,content:n.content,sig:n.sig},t;try{t=Gt(e)}catch{return!1}if(t!==e.id||typeof e.sig!="string")return!1;let r=`${t}:${e.pubkey}:${e.sig}`;return vt.has(r)?(vt.delete(r),vt.set(r,!0),!0):Zt(e)?(vt.size>=Ta&&vt.delete(vt.keys().next().value),vt.set(r,!0),!0):!1}function Pr(n){return Ra.encode(JSON.stringify(n)).length<=16*1024}function ct(n,e){let t=n.tags.filter(r=>r[0]===e);return t.length===1&&t[0].length===2?t[0][1]:null}function Fn(n){return typeof n=="string"&&/^\/media\/[a-z0-9_./-]+$/iu.test(n)&&!n.split("/").includes("..")}function xt(n){return Math.ceil(Math.max(65536,Math.ceil(n/64))/16384)*16384}function _i(n){return n.v===3?3:n.v===2?2:1}function Oi(n){let e=_i(n),t=e>=2;return JSON.stringify({domain:Li[e],v:e,streamEventId:n.streamEventId,swarmId:n.swarmId,key:n.key,rendition:n.rendition,sequence:n.sequence,discontinuity:n.discontinuity,part:n.part,sha256:n.sha256,size:n.size,expiresAt:n.expiresAt,...t?{playlist:n.playlist,mediaType:n.mediaType,encryption:n.encryption}:{},...e===3?{pieceSize:n.pieceSize,pieces:n.pieces}:{}})}function La(n){return JSON.stringify({domain:"relayswarm-commitment-delegation-v1",v:1,streamEventId:n.streamEventId,swarmId:n.swarmId,delegatePubkey:n.delegatePubkey,notBefore:n.notBefore,expiresAt:n.expiresAt,renditions:n.renditions,mediaTypes:n.mediaTypes,allowParts:n.allowParts,maxSegmentBytes:n.maxSegmentBytes})}function _a(n){return JSON.stringify({domain:"relayswarm-commitment-revocation-v1",v:1,streamEventId:n.streamEventId,swarmId:n.swarmId,delegationId:n.delegationId})}function Hr(n){try{return n.kind===30311&&Pr(n)&&Nr(n)&&typeof ct(n,"d")=="string"&&n.tags.some(e=>e.length===3&&e[0]==="relayswarm"&&e[1]==="redistribute"&&e[2]==="1")}catch{return!1}}function Oa(n,{streamEvent:e,swarmId:t,revokedDelegationIds:r=[],delegationRevocations:s=[]},i=Date.now()){try{let o=Math.floor(i/1e3);if(!Hr(e)||!n||!Pr(n)||n.kind!==Ea||n.pubkey!==e.pubkey||!Nr(n)||ct(n,"x")!==t||ct(n,"e")!==e.id||!Number.isSafeInteger(n.created_at)||n.created_at>o+30||!Array.isArray(r)||r.length>256||r.includes(n.id)||!Array.isArray(s)||s.length>256)return null;let a=JSON.parse(n.content);if(n.content!==La(a)||a.domain!=="relayswarm-commitment-delegation-v1"||a.v!==1||a.streamEventId!==e.id||a.swarmId!==t||!zn.test(a.delegatePubkey)||!Number.isSafeInteger(a.notBefore)||a.notBeforeo||!Number.isSafeInteger(a.expiresAt)||a.expiresAt<=o||a.expiresAt<=a.notBefore||a.expiresAt>n.created_at+3600||!Array.isArray(a.renditions)||!a.renditions.length||a.renditions.length>40||new Set(a.renditions).size!==a.renditions.length||a.renditions.some(l=>!(Fn(l)||/^(?:0|[1-9][0-9]{0,3})$/u.test(l)))||!Array.isArray(a.mediaTypes)||!a.mediaTypes.length||a.mediaTypes.length>2||new Set(a.mediaTypes).size!==a.mediaTypes.length||a.mediaTypes.some(l=>!["main","audio"].includes(l))||typeof a.allowParts!="boolean"||!Number.isSafeInteger(a.maxSegmentBytes)||a.maxSegmentBytes<1||a.maxSegmentBytes>16*1024*1024)return null;for(let l of s){if(!l||!Pr(l)||l.kind!==Aa||l.pubkey!==e.pubkey||!Number.isSafeInteger(l.created_at)||l.created_ato+30||!Nr(l)||ct(l,"e")!==n.id||ct(l,"x")!==t)continue;let c=JSON.parse(l.content);if(l.content===_a(c)&&c.domain==="relayswarm-commitment-revocation-v1"&&c.v===1&&c.streamEventId===e.id&&c.swarmId===t&&c.delegationId===n.id)return null}return a}catch{return null}}function Ot(n){try{let e=n.frag.baseurl||n.frag.base?.url;if(typeof e!="string"||e.length>4096)return null;let t=new URL(e);if(!["http:","https:"].includes(t.protocol)||new Set([...t.searchParams.keys()]).size!==[...t.searchParams.keys()].length||t.username||t.password||t.hash||[...t.searchParams].some(([o,a])=>!["_HLS_msn","_HLS_part","_HLS_skip"].includes(o)||!/^(?:[0-9]+|YES|v2)$/u.test(a))||!Fn(t.pathname))return null;let r=n.frag.type??"main";if(!["main","audio"].includes(r))return null;let s=n.frag.decryptdata,i=null;if(s?.method&&s.method!=="NONE"){if(s.method!=="AES-128"||s.keyFormat&&s.keyFormat!=="identity")return null;let o=new URL(s.uri,t);if(o.origin!==t.origin||o.search||o.hash||!Fn(o.pathname)||!s.iv||s.iv.length!==16||Array.from(s.iv).some(a=>!Number.isInteger(a)||a<0||a>255))return null;i={method:"AES-128",keyPath:o.pathname,iv:Array.from(s.iv,a=>a.toString(16).padStart(2,"0")).join(""),keyFormat:"identity"}}return{playlist:t.pathname,mediaType:r,encryption:i}}catch{return null}}function Ii(n,{streamEvent:e,swarmId:t,key:r,context:s,maxSegmentBytes:i,delegation:o,revokedDelegationIds:a,delegationRevocations:l},c=Date.now()){try{let u=Math.floor(c/1e3);if(!Number.isSafeInteger(i)||i<1||i>16*1024*1024||!Hr(e)||!n||n.kind!==Ti||!Pr(n)||!Number.isSafeInteger(n.created_at)||n.created_at>u+30||n.created_at=2;if(n.content!==Oi(d)||d.domain!==Li[f]||![1,2,3].includes(d.v)||d.streamEventId!==e.id||d.swarmId!==t||d.key!==r||d.sequence!==s.frag.sn||d.discontinuity!==(s.frag.cc??0)||d.part!==(s.part?.index??null)||!Number.isSafeInteger(d.sequence)||d.sequence<0||!Number.isSafeInteger(d.discontinuity)||d.discontinuity<0||d.part!==null&&(!Number.isSafeInteger(d.part)||d.part<0)||!zn.test(d.sha256)||!Number.isSafeInteger(d.size)||d.size<1||d.size>i||!Number.isSafeInteger(d.expiresAt)||d.expiresAt<=u||d.expiresAt>u+300||f===3&&(d.pieceSize!==xt(d.size)||!Array.isArray(d.pieces)||d.pieces.length!==Math.ceil(d.size/d.pieceSize)||d.pieces.some(p=>typeof p!="string"||!zn.test(p))))return null;if(g){let p=Ot(s);if(!p||d.rendition!==p.playlist||d.playlist!==p.playlist||d.mediaType!==p.mediaType||JSON.stringify(d.encryption)!==JSON.stringify(p.encryption))return null}else if(d.rendition!==String(s.frag.level)||s.frag.type&&s.frag.type!=="main"||s.frag.decryptdata?.method&&s.frag.decryptdata.method!=="NONE")return null;if(n.pubkey!==e.pubkey){let p=Oa(o,{streamEvent:e,swarmId:t,revokedDelegationIds:a,delegationRevocations:l},c);if(!p||n.pubkey!==p.delegatePubkey||ct(n,"delegation")!==o.id||n.created_atp.expiresAt||!p.renditions.includes(d.rendition)||!p.mediaTypes.includes(g?d.mediaType:"main")||d.part!==null&&!p.allowParts||d.size>p.maxSegmentBytes)return null}return d}catch{return null}}var Ci=new TextEncoder,Ia=new TextDecoder;function Ni(n,e,t){let r=e.byteLength,s=n.rs_alloc(r);try{return new Uint8Array(n.memory.buffer,s,r).set(e),t(s,r)}finally{n.rs_free(s,r)}}var Ca=(n,e)=>new Uint8Array(n.memory.buffer,n.rs_result_ptr(),e);function Pi(n,{size:e,sha256:t,pieces:r,deadline:s,maxHolders:i,originReserveMs:o,peerOnly:a=!1},l,c){if(l()||!Na.every(u=>typeof n[u]=="function")||typeof a!="boolean")return null;if(a)try{if(typeof n.rs_xfer_capabilities!="function"||!(n.rs_xfer_capabilities()&2))return null}catch{return null}try{let u=Ni(n,Ci.encode(JSON.stringify({sha256:t,pieces:r,...a?{peerOnly:!0}:{}})),(d,f)=>n.rs_xfer_new(e,s,i,o,d,f));return u?new jn(n,u,l,c,a):null}catch(u){return c(u),null}}var Na=["rs_xfer_new","rs_xfer_call","rs_xfer_free"],tr={start:0,delivered:1,failed:2,tick:3,state:4,progress:5},jn=class{#r;#t;#e;#s;#d;constructor(e,t,r,s,i=!1){this.#r=e,this.#t=t,this.#e=r,this.#s=s,this.#d=i}start(e,{peers:t,origin:r,sharedFirstByteMs:s=null,sharedRate:i=null,probePeers:o=[]}){let a=!1;try{a=typeof this.#r.rs_xfer_capabilities=="function"&&!!(this.#r.rs_xfer_capabilities()&1)}catch{}let l=new Set(o),c=a?t:t.filter(([u])=>!l.has(u));return this.#i(tr.start,e,-1,0,0,Ci.encode(JSON.stringify({peers:c,origin:this.#d?null:r,sharedFirstByteMs:s,sharedRate:i,...a?{probePeers:o}:{}})))}delivered(e,t,r,s){return this.#i(tr.delivered,e,t,r.start,r.end,s)}failed(e,t){return this.#i(tr.failed,e,t,0,0,qn)}tick(e){return this.#i(tr.tick,e,-1,0,0,qn)}progress(e,t,r){return this.#i(tr.progress,e,t,r,0,qn)}free(){if(this.#t===null)return;let e=this.#t;if(this.#t=null,!this.#e())try{this.#r.rs_xfer_free(e)}catch(t){this.#s(t)}}#i(e,t,r,s,i,o){if(this.#t===null||this.#e())return null;let a=this.#r;try{let l=Ni(a,o,(p,m)=>a.rs_xfer_call(this.#t,e,Math.floor(t),r==="origin"?-1:r,s,i,p,m));if(l<4)throw new Error(`Core transfer refused operation ${e}.`);let c=Ca(a,l),u=new DataView(c.buffer,c.byteOffset,l).getUint32(0,!0),d=JSON.parse(Ia.decode(c.subarray(4,4+u))),f=l>4+u?c.slice(4+u):null;return{commands:d.c.map(p=>p.p?{...p,range:{start:p.p[0],end:p.p[1]}}:p),next:d.next,late:d.late,finished:d.finished,verified:d.verified??null,bytes:f}}catch(l){return this.#s(l),null}}},qn=new Uint8Array(0);var Se={text:0,binary:1,request:2,abort:3,close:4,tick:5,serve:6,bufferedLow:7,sendHave:8,sendHaveChange:9,sendContribution:10,sendFetching:11,state:12,sets:13,requestRange:14,serveRange:15},De={sendText:1,sendBinary:2,closed:3,report:4,resolved:5,haveChanged:6,scheduleChanged:7,serveRequest:8,uploadCancelled:9,progress:10,serveRange:11},Pa=128*1024,Ha=32*1024,Da=new Set(["host","host-stop","admission","rotation","integrity","request-timeout","request-abort","native-failed","native-closed","native-disconnected","channel-close","channel-error","protocol","send-error","serve-error","upload-queue","upload-drain-timeout"]),ht=new TextEncoder,It=new TextDecoder,Wn=new Uint8Array(0),Kn=()=>{try{return globalThis.performance.now()}catch{return null}},Hi=n=>{let e=Math.trunc(Math.max(1,n));return e>=1&&e<=2**31-1?e:1},Dr=class n{get supportsRanges(){return!this.closed}static ABANDON_REASON=at.ABANDON_REASON;#r;#t;#e=-1;#s=null;#d=null;#i=0;#c=!1;#o=!1;#n=new Map;#h=null;#M=!1;#B=0;constructor({pubkey:e,pc:t,channel:r,maxSegmentBytes:s,onRequest:i,onHaveChange:o,onScheduleChange:a,onClose:l,onUploadCancelled:c,maxQueuedRequests:u=4,drainTimeoutMs:d=3e3},f){this.pubkey=e,this.pc=t,this.channel=r,this.maxSegmentBytes=s,this.onRequest=i,this.onHaveChange=o,this.onScheduleChange=a,this.onClose=l,this.onUploadCancelled=c,this.maxQueuedRequests=u,this.drainTimeoutMs=d,this.contribution={serving:!1,rendition:null,at:0},this.fetching=new Map,this.renditions=new Map,this.have=new Set,this.announced=new Map,this.closed=!1,this.closeReason=void 0,this.openedAt=Date.now(),this.lastServedAt=0,this.lastDeliveredAt=0,this.outboundInFlight=0,this.bytesIn=0,this.bytesOut=0,this.#r=f,this.#i=this.openedAt,this.#t=f.newLink(s,u,d,this.#l(),this.openedAt),f.links.add(this),r.binaryType="arraybuffer",r.bufferedAmountLowThreshold=Ha,r.addEventListener("message",g=>{if(this.closed)return;let{data:p}=g;typeof p=="string"?this.#a(Se.text,{bytes:ht.encode(p)}):this.#a(Se.binary,{bytes:p instanceof ArrayBuffer?new Uint8Array(p):ArrayBuffer.isView(p)?new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Wn})}),r.addEventListener("close",()=>this.close("channel-close")),r.addEventListener("error",()=>this.close("channel-error")),r.addEventListener("bufferedamountlow",()=>{this.closed||this.#a(Se.bufferedLow,{a:this.#R()})}),t.addEventListener("connectionstatechange",()=>{let g=t.connectionState;["failed","closed","disconnected"].includes(g)&&this.close(`native-${g}`)})}get kind(){return"wasm"}get busy(){return this.#c}get transferring(){return this.#o}get lastUsefulAt(){return Math.max(this.lastDeliveredAt,this.lastServedAt,this.openedAt)}sendHave(e){this.closed||this.#a(Se.sendHave,{bytes:ht.encode(JSON.stringify([...e]))})}sendHaveChange(e=[],t=[]){this.closed||this.#a(Se.sendHaveChange,{bytes:ht.encode(JSON.stringify({add:[...e],del:[...t]}))})}sendContribution(e,t){this.closed||this.#a(Se.sendContribution,{a:e?1:0,bytes:ht.encode(JSON.stringify(typeof t=="string"?t:null))})}sendFetching(e,t=0){this.closed||this.#a(Se.sendFetching,{a:t,bytes:ht.encode(String(e))})}request(e,t,{signal:r,expectedSize:s,onResult:i,onProgress:o,range:a}={}){let l=Kn(),c=!1,u=(f,g=null)=>{if(!c&&(c=!0,typeof i=="function"))try{let p=null;if(Number.isFinite(l)){let v=Kn();Number.isFinite(v)&&(p=v-l)}let m=g?.receivedBytes??0,b=Number.isFinite(d?.firstByteAt)&&Number.isFinite(l)?d.firstByteAt-l:null;i({outcome:f,elapsedMs:Number.isFinite(p)&&p>=0?p:null,timeoutMs:Number.isFinite(t)&&t>=0?t:null,expectedBytes:Number.isSafeInteger(s)&&s>=0?s:null,receivedBytes:Number.isSafeInteger(m)&&m>=0?m:null,firstByteMs:Number.isFinite(b)&&b>=0?b:null,metadataReceived:g?.metadataReceived===!0,draining:g?.draining===!0,closeReason:Da.has(this.closeReason)?this.closeReason:null})}catch{}},d=null;if(this.closed||this.#c||r?.aborted){let f=Promise.resolve(null);return u(this.closed?"closed":this.#c?"busy":"abort"),f}return new Promise(f=>{let g=()=>{d.id!==null&&!this.closed&&this.#a(Se.abort,{a:d.id,b:r?.reason===n.ABANDON_REASON?1:0})};d={id:null,firstByteAt:null,settled:!1,report:u,onProgress:o,startedAt:l,settle:m=>{d.settled||(d.settled=!0,r?.removeEventListener("abort",g),f(m))}};let p=s===void 0?NaN:Number.isSafeInteger(s)&&s>=0?s:-1;this.#h=d;try{a?this.#a(Se.requestRange,{a:Hi(t),b:a.objectSize,bytes:ht.encode(JSON.stringify([String(e),a.start,a.end]))}):this.#a(Se.request,{a:Hi(t),b:p,bytes:ht.encode(String(e))})}finally{this.#h=null}if(d.id===null){d.settle(null),u("closed");return}d.settled||r?.addEventListener("abort",g,{once:!0})})}close(e="host"){if(!this.closed){if(this.#t===null)return this.#b("host");this.#a(Se.close,{bytes:ht.encode(typeof e=="string"?e:"host")})}}die(){this.#b("host")}#b(e){if(!this.closed){this.closed=!0,this.closeReason=e,this.#t=null,this.#r.links.delete(this),this.#I(),this.fetching.clear(),this.renditions.clear(),this.announced.clear(),this.#c=!1,this.#o=!1;for(let t of this.#n.values())t.settle(null),t.report("closed");this.#n.clear();try{this.channel.close()}catch{}try{this.pc.close()}catch{}this.onClose?.(this)}}#S(){try{return this.channel.readyState==="open"}catch{return!1}}#l(){try{return this.channel.ordered===!0&&this.channel.maxRetransmits===null&&this.channel.maxPacketLifeTime===null}catch{return!1}}#f(){return this.#i=Math.max(this.#i,Date.now()),this.#i}#a(e,{a:t=0,b:r=0,bytes:s=Wn,now:i=this.#f()}={}){if(this.#t===null)return;let o=this.#r.call(this.#t,e,i,(this.#S()?1:0)|(this.#l()?2:0),t,r,s);o&&this.#k(o)}#k({header:e,events:t}){let[r,s,i,o,a,l,c,u,d,f,g,p,m]=e;this.closed=s===1,this.#c=i===1,this.#o=o===1,this.outboundInFlight=a,this.bytesIn=l,this.bytesOut=c,this.openedAt=u,this.lastServedAt=d,this.lastDeliveredAt=f,!Number.isNaN(p)&&this.#h&&(this.#h.id=p,this.#n.set(p,this.#h)),r!==this.#e&&this.#w(r),this.closed&&this.announced.clear();let b=++this.#B;for(let v of t)this.#O(v);if(b===this.#B&&this.#t!==null&&(this.#Y(g),m===1&&this.#R()<=Pa))return this.#a(Se.bufferedLow,{a:this.#R()});this.closed&&!this.#o&&this.#t!==null&&(this.#r.free(this.#t),this.#t=null,this.#r.links.delete(this),this.#I())}#w(e){let t=this.#r.sets(this.#t);if(t){this.#e=e,this.have.clear();for(let r of t.have)this.have.add(r);this.fetching.clear();for(let[r,s]of t.fetching)this.fetching.set(r,s);this.renditions.clear();for(let[r,s]of t.renditions)this.renditions.set(r,s);(t.serving!==this.contribution.serving||t.rendition!==this.contribution.rendition||t.at!==this.contribution.at)&&(this.contribution={serving:t.serving,rendition:t.rendition,at:t.at},t.rendition!==null&&(this.announced.delete(t.rendition),this.announced.size>=8&&this.announced.delete(this.announced.keys().next().value),this.announced.set(t.rendition,t.at))),t.closeReason!==null&&(this.closeReason=t.closeReason)}}#O({tag:e,payload:t,id:r}){let s=i=>new DataView(t.buffer,t.byteOffset,t.byteLength).getFloat64(i*8,!0);switch(e){case De.sendText:{if(this.#M)return;let i=It.decode(t);try{this.channel.send(i)}catch{this.#M=!0,this.close("send-error")}return}case De.sendBinary:{if(this.#M)return;try{this.channel.send(t)}catch{this.#M=!0,this.close("serve-error")}return}case De.closed:{this.closeReason=It.decode(t),this.#I();try{this.channel.close()}catch{}try{this.pc.close()}catch{}this.onClose?.(this);return}case De.report:{let i=JSON.parse(It.decode(t)),o=i.id===null?this.#h:this.#n.get(i.id);if(!o)return;o.report(i.outcome,i),o.settled&&i.id!==null&&this.#n.delete(i.id);return}case De.resolved:{let i=Number.isNaN(r)?this.#h:this.#n.get(r);if(!i)return;i.settle(t);return}case De.haveChanged:{let i=JSON.parse(It.decode(t));this.onHaveChange?.(this,i);return}case De.scheduleChanged:{this.onScheduleChange?.(this);return}case De.serveRequest:case De.serveRange:{let i,o;if(e===De.serveRange){let[a,l,c]=JSON.parse(It.decode(t));i=a,o={start:l,end:c}}else i=It.decode(t);Promise.resolve().then(()=>this.closed?null:o?this.onRequest?.(this,i,o):this.onRequest?.(this,i)).then(a=>this.#v(a,o),()=>{this.close("serve-error"),this.#v(null)});return}case De.uploadCancelled:{this.onUploadCancelled?.(this,s(0));return}case De.progress:{let i=s(0),o=s(1);for(let a of this.#n.values())if(!a.settled&&(a.firstByteAt===null&&(a.firstByteAt=Kn()),typeof a.onProgress=="function"))try{a.onProgress(i,o,Number.isFinite(a.startedAt)?a.firstByteAt-a.startedAt:null)}catch{}return}default:throw new Error(`Unknown core link event ${e}.`)}}#R(){try{return Math.max(0,Number(this.channel.bufferedAmount)||0)}catch{return 0}}#v(e,t){if(this.#t===null)return;let r=this.#R(),s=e?e instanceof Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e instanceof ArrayBuffer?new Uint8Array(e):null:null;if(e&&!s)return this.close("serve-error"),this.#a(Se.serve,{a:0,b:r});if(s&&t&&this.#r.rangeUploads){let i=s.byteLength,o=xt(i);return i<1||i>this.maxSegmentBytes||!Number.isSafeInteger(t.start)||!Number.isSafeInteger(t.end)||t.start<0||t.start>=t.end||t.end>Math.ceil(i/o)?this.#a(Se.serve,{a:0,b:r}):this.#a(Se.serveRange,{a:i,b:r,bytes:s.subarray(t.start*o,Math.min(i,t.end*o))})}this.#a(Se.serve,{a:s?1:0,b:r,bytes:s??Wn})}#Y(e){if(Number.isNaN(e))return this.#I();this.#s!==null&&this.#d===e||(this.#I(),this.#d=e,this.#s=globalThis.setTimeout(()=>{this.#s=null,this.#d=null,this.#i=Math.max(this.#i,e),this.#a(Se.tick)},Math.max(0,e-this.#f())))}#I(){this.#s!==null&&globalThis.clearTimeout(this.#s),this.#s=null,this.#d=null}};var Ua=/^[0-9a-f]{64}$/u,ce={context:0,demand:1,hint:2,holderMiss:3,holderAhead:4,stale:5,forget:6,current:7,candidates:8,choose:9,hinted:10,begin:11,valid:12,replaced:13,allocated:14,abandoned:15,failed:16,end:17,verified:18,live:19,reserved:20,suppresses:21,snapshot:22,clear:23,rearm:24},za=6e4,Fa=2e4,qa=new Set([ce.stale,ce.current,ce.valid,ce.live,ce.reserved,ce.suppresses]),rr=class extends Error{constructor(e){super("Core discovery failed.",{cause:e})}},Ur=class{#r;#t;#e=null;#s=new Map;#d=new Map;#i=new WeakMap;#c=null;#o=null;#n=new WeakMap;#h=new WeakMap;#M=new Map;#B=1;#b=null;#S=null;constructor(e,t,r=()=>Date.now()){this.#r=e,this.#t=t,this.clock=r,this.counters={checks:0,replacements:0,expired:0,opened:0,verified:0,staleHolder:0,staleBlocked:0,heldMiss:0,rearmed:0,victimUnhelpful:0,victimServing:0,victimConsumer:0,unmetNoHint:0,unmetIneligible:0}}get kind(){return this.#e?"js":"wasm"}get contexts(){return this.#e?this.#e.contexts:this.#s}get window(){return this.#e?this.#e.window:this.#c}get candidates(){return this.#e?this.#e.candidates:new Map(this.#f(ce.candidates,[]).map(e=>[e.pubkey,e]))}retire(){this.#e||(this.#S=null,this.#e=new _t(this.clock),this.#e.counters=this.counters)}#l(e,t){if(this.#e)return t(this.#e);try{return e()}catch(r){if(!(r instanceof rr))throw r;this.retire();try{this.#t?.(r.cause)}catch{}return t(this.#e)}}#f(e,t){try{let r=this.#r(e,this.clock(),t);if(e===ce.candidates)return r.map(([s,i,o,a])=>({pubkey:s,have:i,ticket:o,at:a}));if(qa.has(e)&&typeof r!="boolean")throw new TypeError(`Core discovery answered operation ${e} with ${typeof r}.`);return r}catch(r){throw new rr(r)}}#a(e,t){try{let{r,s}=this.#r(e,this.clock(),t);return this.#k(s),r}catch(r){throw new rr(r)}}#k({c:e,w:t,n:r}){let s=new Map;this.#s=new Map;for(let i of e){let o=this.#d.get(i.id);o||(o={mediaType:i.mediaType,rendition:i.rendition,keys:[],lastDemandAt:null,activityAt:0,spent:!1},this.#i.set(o,i.id)),(o.keys.length!==i.keys.length||o.keys.some((a,l)=>a!==i.keys[l]))&&(o.keys=i.keys),Object.assign(o,{lastDemandAt:i.lastDemandAt,activityAt:i.activityAt,spent:i.spent,spentAt:i.spentAt}),s.set(i.id,o),this.#s.set(i.mediaType,o)}if(!t)this.#c=null,this.#o=null;else{let i=s.get(t.context)??this.#d.get(t.context);i&&s.set(t.context,i),this.#o!==t.id&&(this.#c={context:i,createdAt:t.createdAt,expiresAt:t.expiresAt,attempt:null,vacant:!1,victim:null,timer:null},this.#o=t.id);let o=this.#c;Object.assign(o,{context:i,expiresAt:t.expiresAt,vacant:t.vacant,victim:t.victim}),t.attempt?(!o.attempt||this.#n.get(o.attempt)!==t.attempt.id)&&(o.attempt={window:o,pubkey:t.attempt.pubkey,ticket:t.attempt.ticket,key:t.attempt.key,dial:null,negotiation:null},this.#n.set(o.attempt,t.attempt.id)):o.attempt=null}this.#d=s,[this.counters.checks,this.counters.replacements,this.counters.verified,this.counters.rearmed,this.counters.unmetNoHint,this.counters.unmetIneligible]=r}#w(e){return e?this.#i.get(e)??null:null}#O(e,t){let s=e===null||typeof e!="object"&&typeof e!="function"?this.#M:this.#h,i=s.get(e);return i===void 0&&t&&s.set(e,i=this.#B++),i}#R(e){let t=this.clock();return this.#S??=this.#f(ce.candidates,[]),this.#S.filter(r=>t>=r.at&&t-r.atr.pubkey)}#v(e){if(!e)return this.#b=null;let[t,r,s,i]=e.candidate,o=this.#d.get(e.context);return this.#b=o?{context:o,candidate:{pubkey:t,have:r,ticket:s,at:i},key:e.key}:null}context(e,t){return e!=="main"&&e!=="audio"?null:this.#l(()=>{let r=this.#a(ce.context,[e,String(t)]);return this.#d.get(r)??null},r=>r.context(e,t))}demand(e,t,r){return this.#l(()=>{if(typeof r!="string"){this.context(e,t);return}if(e!=="main"&&e!=="audio")return;let s=this.#a(ce.demand,[e,String(t),r]);return this.#d.get(s)??void 0},s=>s.demand(e,t,r))}hint(e,t,r){typeof e!="string"||!Ua.test(e)||!Array.isArray(t)||this.#l(()=>{this.#S=null,this.#f(ce.hint,[e,t.filter(s=>typeof s=="string"),ye(r)?r:null])},s=>s.hint(e,t,r))}holderMiss(e,t,r){if(!(typeof t!="string"||typeof r!="string"))return this.#l(()=>this.#f(ce.holderMiss,[this.#w(e),t,r]),s=>s.holderMiss(e,t,r))}holderDelivered(e,t){this.holderAhead(e,t)}spent(e){return this.#e?this.#e.spent(e):e?.spentAt!==null&&e?.spentAt!==void 0}rearm(e,t){return this.#l(()=>{let r=this.#w(e),s=this.clock();return r===null||!this.spent(e)||sr.rearm(e,t))}holderAhead(e,t){typeof t=="string"&&this.#l(()=>{this.#f(ce.holderAhead,[this.#w(e),t])},r=>r.holderAhead(e,t))}stale(e,t){return typeof t!="string"?!1:this.#l(()=>this.#f(ce.stale,[this.#w(e),t]),r=>r.stale(e,t))}forget(e){typeof e=="string"&&this.#l(()=>{this.#f(ce.forget,[e])},t=>t.forget(e))}current(e){return this.#l(()=>this.#w(e)!==null&&this.#f(ce.current,[this.#w(e)]),t=>t.current(e))}choose(e,t,r){return this.#l(()=>{if(this.#c?.attempt)return this.#b=null;let i=(this.#c?[this.#c.context]:[...this.#s.values()]).filter(o=>this.#f(ce.current,[this.#w(o)])&&t(o)).map(o=>o.mediaType);return i.length===0?this.#b=null:this.#v(this.#a(ce.choose,[this.#R(e),i,!!r]))},s=>s.choose(e,t,r))}hinted(e,t){return this.#l(()=>{let r=this.#w(e);return r===null?this.#b=null:this.#v(this.#f(ce.hinted,[r,this.#R(t)]))},r=>r.hinted(e,t))}begin(e){return this.#l(()=>!e||e!==this.#b?null:(this.#b=null,this.#a(ce.begin,[])===null?null:this.#c?.attempt??null),t=>t.begin(e))}valid(e){return this.#l(()=>{let t=e?this.#n.get(e):void 0;return t!==void 0&&this.#f(ce.valid,[t])},t=>t.valid(e))}replaced(e,t){return this.#l(()=>{let r=e?this.#n.get(e):void 0;return r!==void 0&&this.#a(ce.replaced,[r,typeof t=="string"?t:null])},r=>r.replaced(e,t))}allocated(e,t){this.#l(()=>{e.dial=t,e.window.vacant=!1;let r=this.#n.get(e);r!==void 0&&this.#a(ce.allocated,[r,this.#O(t,!0)])},r=>r.allocated(e,t))}abandoned(e){this.#l(()=>{let t=e?this.#n.get(e):void 0;t!==void 0&&this.#a(ce.abandoned,[t])},t=>t.abandoned(e))}failed(e){this.#l(()=>{let t=this.#O(e,!1);t!==void 0&&this.#a(ce.failed,[t])},t=>t.failed(e))}end(e=this.window){return this.#l(()=>!!e&&e===this.#c&&this.#a(ce.end,[]),t=>t.end(e))}verified(e){return this.#l(()=>{let t=this.#w(e);return t!==null&&this.#s.get(e.mediaType)===e&&this.#a(ce.verified,[t])},t=>t.verified(e))}live(e=this.window){return this.#l(()=>!!e&&e===this.#c&&this.#f(ce.live,[]),t=>t.live(e))}reserved(){return this.#l(()=>this.#f(ce.reserved,[]),e=>e.reserved())}suppresses(e){return typeof e!="string"?!1:this.#l(()=>this.#f(ce.suppresses,[e]),t=>t.suppresses(e))}snapshot(){return this.#l(()=>({...this.#f(ce.snapshot,[]),counters:{...this.counters}}),e=>e.snapshot())}clear(){this.#l(()=>{this.#b=null,this.#S=null,this.#a(ce.clear,[])},e=>e.clear())}};var ja=0,Wa=1,Ka=2,Va=3,Di=new TextEncoder,Vn=new TextDecoder;function $a(n){return{sequence:n.frag.sn??null,discontinuity:n.frag.cc??0,part:n.part?.index??null,level:String(n.frag.level),fragType:n.frag.type??null,decryptMethod:n.frag.decryptdata?.method??null,media:Ot(n)}}async function Ga(n){if(n instanceof WebAssembly.Module)return{instance:await WebAssembly.instantiate(n,{}),module:n};if(n instanceof ArrayBuffer||ArrayBuffer.isView(n))return WebAssembly.instantiate(n,{});let e=n instanceof URL?n.href:n;if(typeof e!="string")throw new TypeError("coreWasm must be a URL, bytes or a WebAssembly.Module.");let t=await fetch(e,{credentials:"same-origin"});if(!t.ok)throw new Error(`Core module unavailable (${t.status}).`);if(typeof WebAssembly.instantiateStreaming=="function")try{return await WebAssembly.instantiateStreaming(t.clone(),{})}catch{}return WebAssembly.instantiate(await t.arrayBuffer(),{})}var Ya=["rs_sel_observe","rs_sel_record","rs_sel_mark","rs_sel_forget","rs_sel_select","rs_sel_state","rs_sel_project","rs_sel_minimum","rs_sel_estimate","rs_sel_summary","rs_link_new","rs_link_free","rs_link_call","rs_disc_call"],Ui=13,Za=15,$n=13,Fi=$n*8,Xa=5,Ct=n=>Number.isNaN(n)?null:n,zi=(n,e)=>new Float64Array(n.memory.buffer,e,6);function zr(n,e,t){let r=e.byteLength,s=n.rs_alloc(r);try{return new Uint8Array(n.memory.buffer,s,r).set(e),t(s,r)}finally{n.rs_free(s,r)}}var Fr=(n,e)=>new Uint8Array(n.memory.buffer,n.rs_result_ptr(),e);function Ja(n,e){let t=Fr(n,e),r=new DataView(t.buffer,t.byteOffset,e),s=new Array($n);for(let o=0;o<$n;o++)s[o]=r.getFloat64(o*8,!0);let i=[];for(let o=Fi;oe)throw new Error("Core link frame has a truncated resolution.");i.push({tag:a,id:r.getFloat64(l,!0),payload:t[l+8]===1?t.slice(l+9,c):null})}return{header:s,events:i}}var Gn=class{#r;#t;#e=null;#s=new WeakMap;#d=0;constructor(e,t){this.#r=e,this.#t=t}get kind(){return this.#e?"js":"wasm"}retire(){this.#e??=new wt}#i(e,t){if(this.#e)return t(this.#e);try{return e(this.#r)}catch(r){return this.#e=new wt,this.#t?.(r),t(this.#e)}}#c(e){let t=this.#s.get(e);return t===void 0&&this.#s.set(e,t=this.#d++),t}#o(e){return this.#i(t=>zi(t,t.rs_sel_state())[e],t=>[t.firstByteMs(),t.rate(),t.lastObservedAt,t.turn,t.order][e]??NaN)}get lastObservedAt(){return this.#o(2)}get turn(){return this.#o(3)}get order(){return this.#o(4)}firstByteMs(){return Ct(this.#o(0))}rate(){return Ct(this.#o(1))}observe({firstByteMs:e=null,bytes:t=0,flowMs:r=0,totalFlowMs:s=r}={}){this.#i(i=>i.rs_sel_observe(Date.now(),Number.isFinite(e)?e:NaN,t,r,s||0),i=>i.observe({firstByteMs:e,bytes:t,flowMs:r,totalFlowMs:s}))}record(e,t,r=0){this.#i(s=>s.rs_sel_record(Date.now(),this.#c(e),t,r),s=>s.record(e,t,r))}markSelected(e){this.#i(t=>t.rs_sel_mark(this.#c(e)),t=>t.markSelected(e))}forget(e){let t=this.#s.get(e);this.#i(r=>{t!==void 0&&r.rs_sel_forget(t)},r=>r.forget(e))}projectMs(e){return this.#i(t=>Ct(t.rs_sel_project(e)),t=>t.projectMs(e))}minimumMs(e){return this.#i(t=>t.rs_sel_minimum(e),t=>t.minimumMs(e))}estimate(e,t){return this.#i(r=>Ct(r.rs_sel_estimate(this.#c(e),t)),r=>r.estimate(e,t))}summary(e){return this.#i(t=>{let[r,s,i,o,a,l]=zi(t,t.rs_sel_summary(this.#c(e)));return{attempts:r,latencyMs:Ct(s),throughputBytesPerSecond:Ct(i),failureRate:o,consecutiveFailures:a,lastSelected:l}},t=>t.summary(e))}select(e,t,r,s,i=1/0){return this.#i(o=>{let a=[...e].filter(d=>!d.closed&&!d.busy&&!r.has(d.pubkey)&&d.have.has(t)),l=a.map(d=>this.#c(d)),c=l.length*4,u=o.rs_alloc(c);try{let d=new DataView(o.memory.buffer,u,c);l.forEach((g,p)=>d.setUint32(p*4,g,!0));let f=o.rs_sel_select(u,l.length,s,i);return f<0?null:a[l.indexOf(f)]}finally{o.rs_free(u,c)}},o=>o.select(e,t,r,s,i))}};async function qi(n,{onFailure:e}={}){let{instance:t,module:r}=await Ga(n),s=t.exports;for(let m of["memory","rs_alloc","rs_free","rs_call","rs_result_ptr",...Ya])if(!s[m])throw new Error(`Core module lacks ${m}.`);let i=!1,o=null,a=null,l=()=>{if(!i){i=!0,o?.retire(),a?.retire();for(let m of[...u.links])m.die()}},c=m=>{if(!i){l();try{e?.(m)}catch{}}},u={links:new Set,rangeUploads:typeof s.rs_link_serve_range=="function",newLink(m,b,v,w,T){if(i)throw new Error("The core has been retired.");return s.rs_link_new(m,b,v,w?1:0,T)},free(m){if(!i)try{s.rs_link_free(m)}catch(b){c(b)}},call(m,b,v,w,T,O,K){if(i)return null;try{let A=zr(s,K,(k,W)=>b===Za&&u.rangeUploads?s.rs_link_serve_range(m,v,w,T,O,k,W):s.rs_link_call(m,b,v,w,T,O,k,W));if(A<0||As.rs_link_call(m,Ui,0,0,0,0,v,w));if(b<0)throw new Error(`Core link ${m} refused operation ${Ui}.`);return JSON.parse(Vn.decode(Fr(s,b)))}catch(b){return c(b),null}}};function d(m,b){let v;try{v=Di.encode(JSON.stringify(b))}catch{return null}let w=zr(s,v,(T,O)=>s.rs_call(m,T,O));return w<0?null:JSON.parse(Vn.decode(Fr(s,w)))}function f(m,b,v){if(i)throw new Error("The core has been retired.");let w=Di.encode(JSON.stringify(v)),T=zr(s,w,(O,K)=>s.rs_disc_call(m,b,O,K));if(T<0)throw new Error(`Core discovery refused operation ${m}.`);return JSON.parse(Vn.decode(Fr(s,T)))}let g=({streamEvent:m,swarmId:b,revokedDelegationIds:v=[],delegationRevocations:w=[]})=>({streamEvent:m,swarmId:b,revokedDelegationIds:v,delegationRevocations:w}),p=Object.freeze({kind:"wasm",validStreamAuthorisation:m=>d(ja,[m])===!0,verifyCommitmentDelegation:(m,b,v=Date.now())=>d(Wa,[m??null,g(b),v]),verifySegmentCommitment(m,b,v=Date.now()){let w;try{w=$a(b.context)}catch{return null}return d(Ka,[m??null,{...g(b),key:b.key,context:w,maxSegmentBytes:b.maxSegmentBytes,delegation:b.delegation??null},v])}});return Object.freeze({module:r,verifier:p,playerHint(m){if(i)return null;try{return d(Va,m)}catch(b){return c(b),null}},retire:l,get retired(){return i},peerSelection(){if(o)throw new Error("This core instance already has a peer selection.");return o=new Gn(s,c)},neighbourDiscovery(m){if(a)throw new Error("This core instance already has a neighbour discovery.");if(i)throw new Error("The core has been retired.");return a=new Ur(f,c,m)},peerLink(m){return new Dr(m,u)},transfer(m){return Pi(s,m,()=>i,c)}})}var Qa=new Uint8Array(0);var el=Object.freeze({maxTransfers:2,maxSegmentBytes:16777216,maxActiveBytes:33554432,maxPending:32,maxPendingBytes:33554432,initTimeoutMs:5e3,operationTimeoutMs:5e3}),tl=Object.freeze({maxTransfers:4,maxSegmentBytes:32*1048576,maxActiveBytes:64*1048576,maxPending:128,maxPendingBytes:64*1048576,initTimeoutMs:3e4,operationTimeoutMs:3e4}),ji=n=>typeof n=="string"&&n.length===64&&/^[a-f0-9]{64}$/.test(n),je=n=>Number.isSafeInteger(n)&&n>=0,sr=n=>Number.isFinite(n)&&n>=0&&n<=Number.MAX_SAFE_INTEGER,nr=n=>n===null||sr(n),rl=(n,e)=>n&&Array.isArray(n.commands)&&n.commands.length<=1024&&n.commands.every(t=>t&&["request","origin","cancel","abandon","ban","deliver","fail"].includes(t.t))&&(n.next===null||sr(n.next))&&typeof n.late=="boolean"&&typeof n.finished=="boolean"&&(n.verified===null||je(n.verified)&&n.verified<=e)&&(n.bytes===null||n.bytes instanceof Uint8Array&&n.bytes.byteLength<=e),fe=class extends Error{constructor(e){super(`Core transfer worker: ${e}.`),this.name="CoreTransferWorkerError",this.code=e}},Nt=()=>new DOMException("Core transfer was cancelled.","AbortError");function nl(n={}){let e={};for(let[t,r]of Object.entries(el)){let s=n[t]??r;if(!Number.isSafeInteger(s)||s<1||s>tl[t])throw new fe("invalid-limits");e[t]=s}return Object.freeze(e)}function sl(n,e){if(!n||!Array.isArray(n.pieces)||n.pieces.length<1||n.pieces.length>256)throw new fe("invalid-transfer");let t=n&&{size:n.size,sha256:n.sha256,pieces:n.pieces?.slice(),deadline:n.deadline,maxHolders:n.maxHolders,originReserveMs:n.originReserveMs,...n.peerOnly===!0?{peerOnly:!0}:{}};if(!t||!je(t.size)||t.size<1||t.size>e.maxSegmentBytes||!ji(t.sha256)||!Array.isArray(t.pieces)||t.pieces.length<1||t.pieces.length>256||!t.pieces.every(ji)||!sr(t.deadline)||!je(t.maxHolders)||t.maxHolders<1||t.maxHolders>32||!sr(t.originReserveMs)||n.peerOnly!==void 0&&typeof n.peerOnly!="boolean")throw new fe("invalid-transfer");return t}function il(n,e,t,r=!1){let[s,i,o]=e;if(!sr(s))throw new fe("invalid-operation");if(n==="start"){let a=i;if(!a||!Array.isArray(a.peers)||a.peers.length>32||!a.peers.every(l=>Array.isArray(l)&&l.length===3&&je(l[0])&&nr(l[1])&&nr(l[2]))||(r?a.origin!=null:!Array.isArray(a.origin)||a.origin.length!==2||!a.origin.every(nr))||!nr(a.sharedFirstByteMs??null)||!nr(a.sharedRate??null)||!Array.isArray(a.probePeers??[])||(a.probePeers?.length??0)>32||!(a.probePeers??[]).every(je))throw new fe("invalid-operation");return[s,{peers:a.peers.map(l=>[...l]),origin:r?null:[...a.origin],sharedFirstByteMs:a.sharedFirstByteMs??null,sharedRate:a.sharedRate??null,probePeers:[...a.probePeers??[]]}]}if(n==="tick")return[s];if(i!=="origin"&&!je(i))throw new fe("invalid-operation");if(r&&i==="origin")throw new fe("invalid-operation");if(n==="failed")return[s,i];if(n==="progress"&&je(o)&&o<=t)return[s,i,o];if(n==="delivered"&&o&&je(o.start)&&je(o.end)&&o.start0&&e.length<=2048)||typeof globalThis.Worker!="function"))throw new fe("worker-unavailable");let a=t??((k,W)=>new Worker(k,W)),l;try{l=a(e,{type:"module",name:"relayswarm-transfer"})}catch{throw new fe("worker-unavailable")}let c="loading",u=null,d=0,f=0,g=0,p=0,m=new Map,b=new Map,v=k=>{k.signal?.removeEventListener("abort",k.onAbort),b.get(k.id)===k&&(b.delete(k.id),p-=k.size)},w=(k,W=!0)=>{if(!(c==="stopped"||c==="failed")){c=W?"failed":"stopped",u=k.code??k.name,l.removeEventListener("message",K),l.removeEventListener("error",T),l.removeEventListener("messageerror",T),r?.removeEventListener("abort",O);for(let _ of m.values())clearTimeout(_.timer),_.settled||_.reject(k);m.clear(),g=0;for(let _ of b.values())_.closed=!0,v(_);try{l.terminate()?.catch?.(()=>{})}catch{}if(W)try{s?.(k)?.catch?.(()=>{})}catch{}}},T=k=>{k?.preventDefault?.(),w(new fe("worker-error"))},O=()=>w(Nt(),!1),K=({data:k})=>{if(!k||k.v!==1||!je(k.id)||!m.has(k.id))return;let W=m.get(k.id);if(m.delete(k.id),g-=W.bytes,clearTimeout(W.timer),k.ok!==!0){let _=new fe(typeof k.error=="string"&&/^[a-z-]{1,40}$/.test(k.error)?k.error:"invalid-response");W.settled||W.reject(_),(k.fatal||k.ok!==!1)&&w(_)}else if(["init","new","free"].includes(W.op)?k.result!==!0:!rl(k.result,W.size)){let _=new fe("invalid-response");W.settled||W.reject(_),w(_)}else W.settled||W.resolve(k.result)},A=(k,W,_,F=0,P=[],N=!1)=>c==="stopped"||c==="failed"?Promise.reject(new fe("closed")):!N&&m.size>=o.maxPending||g+F>o.maxPendingBytes?Promise.reject(new fe("queue-limit")):new Promise((h,x)=>{let S=++d,M={resolve:h,reject:x,handle:W,bytes:F,op:k,size:b.get(W)?.size??o.maxSegmentBytes,settled:!1,timer:setTimeout(()=>w(new fe(k==="init"?"init-timeout":"operation-timeout")),k==="init"?o.initTimeoutMs:o.operationTimeoutMs)};m.set(S,M),g+=F;try{l.postMessage({v:1,id:S,op:k,handle:W,input:_},P)}catch{w(new fe("worker-message"))}});l.addEventListener("message",K),l.addEventListener("error",T),l.addEventListener("messageerror",T),r?.addEventListener("abort",O,{once:!0}),r?.aborted&&O();try{await A("init",null,{module:n,limits:o})}catch(k){throw w(k),k}if(c!=="loading")throw new fe("closed");return c="ready",Object.freeze({snapshot:()=>({state:c,reason:u,transfers:b.size,activeBytes:p,pending:m.size,pendingBytes:g}),stop:O,async transfer(k,{signal:W}={}){if(c!=="ready")throw new fe("closed");if(W?.aborted)throw Nt();let _=sl(k,o);if(b.size>=o.maxTransfers||p+_.size>o.maxActiveBytes)throw new fe("transfer-limit");let F={id:++f,size:_.size,closed:!1,signal:W,release:null};b.set(F.id,F),p+=_.size;let P=()=>{if(F.release)return F.release;F.closed=!0;for(let h of m.values())h.handle===F.id&&!h.settled&&(h.settled=!0,h.reject(Nt()));return F.release=A("free",F.id,null,0,[],!0).then(()=>!0,()=>!1).finally(()=>v(F))};F.onAbort=()=>{P()},W?.addEventListener("abort",F.onAbort,{once:!0});try{await A("new",F.id,_)}catch(h){throw F.closed||v(F),h}if(F.closed||W?.aborted)throw P(),Nt();let N=async(h,x)=>{if(F.closed)throw new fe("closed-transfer");try{let S=il(h,x,o.maxSegmentBytes,_.peerOnly===!0),M=0,H=[];if(h==="delivered"){if(M=S[3].byteLength,g+M>o.maxPendingBytes)throw new fe("queue-limit");S[3]=S[3].slice(),H=[S[3].buffer]}let D=await A(h,F.id,S,M,H);if(F.closed)throw Nt();return D}catch(S){throw P(),S}};return Object.freeze({start:(h,x)=>N("start",[h,x]),delivered:(h,x,S,M)=>N("delivered",[h,x,S,M]),failed:(h,x)=>N("failed",[h,x]),progress:(h,x,S)=>N("progress",[h,x,S]),tick:h=>N("tick",[h]),free:P,cancel:P,get closed(){return F.closed}})}})}function Ki(n,e,t){if(!Number.isSafeInteger(e)||!Number.isSafeInteger(t)||e<0||t<=e)return null;let r=Number.isSafeInteger(n?.rangeEnd)&&n.rangeEnd>0,s=r&&Number.isSafeInteger(n.rangeStart)?n.rangeStart:0;return r&&s+t>n.rangeEnd?null:{first:s+e,last:s+t-1}}function ut(n,e,t,r,s=null,i=null){if(typeof n=="function")try{let o=n({outcome:e,expectedBytes:Number.isSafeInteger(r-t)&&r>t?r-t:null,receivedBytes:Number.isSafeInteger(s)&&s>=0?s:null,httpStatus:Number.isInteger(i)&&i>=100&&i<=599?i:null});o&&typeof o.then=="function"&&Promise.resolve(o).catch(()=>{})}catch{}}function Vi(n,e,t,r,{signal:s,onIgnored:i,onResult:o}={}){let a=Ki(e,t,r);return!a||typeof n?.Loader!="function"||typeof e?.url!="string"||s?.aborted?(ut(o,s?.aborted?"abort":"invalid-request",t,r),Promise.resolve(null)):new Promise(l=>{let c=null,u=!1,d=(p,m,b=p?.byteLength??null,v=null)=>{if(!u){u=!0,s?.removeEventListener("abort",f);try{c?.destroy?.()}catch{}ut(o,m,t,r,b,v),l(p)}},f=()=>{try{c?.abort?.()}catch{}d(null,"abort")},g=p=>{let m=p instanceof ArrayBuffer?new Uint8Array(p):ArrayBuffer.isView(p)?new Uint8Array(p.buffer,p.byteOffset,p.byteLength):null;return m&&m.byteLength===r-t?m.slice():null};try{c=new n.Loader(n.config),s?.addEventListener("abort",f,{once:!0}),c.load({...e,responseType:"arraybuffer",rangeStart:a.first,rangeEnd:a.last+1},n.loaderConfig??{},{onSuccess:p=>{if(s?.aborted)return d(null,"abort");let m=g(p?.data);if(!m&&!u)try{i?.()}catch{}d(m,m?"payload":"wrong-size",p?.data?.byteLength??null,p?.code)},onError:p=>d(null,s?.aborted?"abort":"error",null,p?.code),onTimeout:()=>d(null,s?.aborted?"abort":"timeout"),onAbort:()=>d(null,"abort")})}catch{d(null,"exception")}})}function ol(n,{first:e,last:t}){if(n===null)return!0;let r=/^bytes (\d+)-(\d+)\/(\d+|\*)$/u.exec(n.trim());return!!r&&Number(r[1])===e&&Number(r[2])===t}async function $i(n,e,t,{signal:r,onIgnored:s,onResult:i,fetchImpl:o=globalThis.fetch}={}){let a=Ki(n,e,t);if(!a||typeof n?.url!="string"||typeof o!="function"||r?.aborted)return ut(i,r?.aborted?"abort":"invalid-request",e,t),null;let l;try{l=await o(n.url,{headers:{Range:`bytes=${a.first}-${a.last}`},signal:r,credentials:"same-origin"})}catch{return ut(i,r?.aborted?"abort":"error",e,t),null}let c=(u=null)=>{try{s?.()}catch{}return ut(i,"wrong-size",e,t,u,l.status),null};try{if(l.status!==206||!ol(l.headers.get("content-range"),a)){try{await l.body?.cancel()}catch{}return l.status===200||l.status===206?c():(ut(i,"error",e,t,null,l.status),null)}let u=new Uint8Array(await l.arrayBuffer());return u.byteLength!==t-e?c(u.byteLength):(ut(i,"payload",e,t,u.byteLength,l.status),u)}catch{return ut(i,r?.aborted?"abort":"error",e,t,null,l?.status),null}}var ke=Symbol("relayswarm-warm-ahead"),Fe=24*1024*1024,Gi=3,Yn=4,Yi=8e3,qr=12e3,al=100,ft=n=>{let{start:e,duration:t}=n?.context?.frag??{};return Number.isFinite(e)&&e>=0&&Number.isFinite(t)&&t>0&&Number.isFinite(e+t)},Zn=(n,e)=>ft(n)&&n.context.frag.start<=e&&en===e||Math.abs(n-e)<=Math.min(1e-9,32*Number.EPSILON*Math.max(1,Math.abs(n),Math.abs(e))),dt=(n,e)=>n?.key===e?.key&&n?.scope===e?.scope&&ft(n)&&ft(e)&&Zi(n.context.frag.start,e.context.frag.start)&&Zi(n.context.frag.duration,e.context.frag.duration),ll=(n,e,t,r)=>{try{let{start:s,end:i}=n.loading;return n.aborted!==!0&&n.loaded===e&&[t,r,s,i].every(Number.isFinite)&&t>=0&&t<=s&&si!==void 0&&i!==0)||e.type!=="main"||!Number.isSafeInteger(e.level)||e.level<0||!Number.isSafeInteger(e.cc??0)||e.decryptdata?.method&&e.decryptdata.method!=="NONE")return null;let t=new URL(n.url??e.url),r=e.baseurl??e.base?.url;return!["http:","https:"].includes(t.protocol)||t.username||t.password||t.hash||typeof r!="string"?null:{context:{...n,url:t.href,frag:{sn:e.sn,cc:e.cc??0,type:e.type,level:e.level,url:t.href,baseurl:r,start:e.start,duration:e.duration,byteRangeStartOffset:e.byteRangeStartOffset,byteRangeEndOffset:e.byteRangeEndOffset},part:null,responseType:"arraybuffer"},key:JSON.stringify([t.href,r,e.type,e.level,e.sn,e.cc??0,0,0]),scope:JSON.stringify([r,e.type,e.level])}}catch{return null}}function Xi({Loader:n,next:e,authorise:t,verify:r,reserve:s=()=>!0,onVerified:i,onReuse:o,reuseBudget:a=()=>0,allowed:l=()=>!0,steady:c=!0,startupTarget:u=null,startupCommit:d=null,startupMaxBytes:f=Fe,startupRecovery:g=()=>2e3}){if(!Number.isSafeInteger(f)||f32*1024*1024||f!==Fe&&typeof u!="function")throw new RangeError("Invalid startup byte budget");let p=!1,m=0,b=null,v=null,w=[],T,O,K=null,A=0,k=new Map,W=new Set,_=new Map,F=new Set,P=new Set,N=new Map,h={enabled:typeof u=="function",state:u?"idle":"off",reason:null,owner:null,terminal:null,own:null,permit:null,response:null,verified:!1,reserved:0,controller:null,timer:null,poll:null,plan:[],cursor:null,frozenStart:null,hopAvailable:!0,checking:!1,targetTime:null,verifiedStart:null,verifiedEnd:null,requiredHeadroomMs:null,planningServiceMs:null,released:0,failures:0,cancellations:0,commitStarted:!1,commitCompleted:!1},x={started:0,verified:0,rejected:0,cancelled:0,coalesced:0,promotions:0,localReuseBytes:0,verifiedBytes:0,verifiedPeerBytes:0,consumedPeerBytes:0,cacheBytes:0,highWaterBytes:0},S=()=>[..._.values()].reduce((y,E)=>y+E.reserved,0),M=()=>h.reserved+S(),H=()=>h.state==="buffering"?f:Fe,D=y=>x.cacheBytes+S()+y<=Fe&&x.cacheBytes+M()+y<=H(),B=()=>new Set([...k.keys(),..._.keys(),...h.owner?[h.own.key]:[]]).size,U=()=>h.state==="buffering"?Yn:Gi,C=y=>_.get(y.key)===y&&!y.finished,z=y=>{let E=k.get(y);E&&(x.cacheBytes-=E.data.byteLength,k.delete(y))},ee=(y,E)=>{C(y)&&(y.finished=!0,_.delete(y.key),F.delete(y),b===y&&(b=null),y.reserved=0,y.finish(E),h.checking&&(h.recheck=!0),Ve(),queueMicrotask(ne))},te=y=>{C(y)&&(x.cancelled++,y.cancel(),ee(y,null))},$=()=>{(h.state==="idle"||h.state==="buffering")&&se("cancelled","cleared",!p),h.planningServiceMs=null,m++,w=[],K=null;for(let y of[..._.values()])te(y);for(let y of k.keys())z(y);for(let y of[...P])y(!0)},ne=()=>{if(p||b||!l()||!w.length||W.size+F.size>1||!c&&h.state!=="buffering"||h.state==="buffering"&&(!h.permit||h.checking)||h.state==="buffering"&&!Ut()||h.state==="buffering"&&B()>=U())return;let y=w.shift();if(k.has(y.key)||_.has(y.key)){queueMicrotask(ne);return}for(;B()>=Gi&&k.size&&h.state!=="buffering";)z(k.keys().next().value);if(B()>=U())return;let E=new AbortController,R=m,q=T,L=O,j,Y,Q,V={...y,reserved:0,finished:!1,waiters:new Set,genuineAt:null,promise:new Promise(X=>{Q=X}),noteDemand(){V.genuineAt??=performance.now(),y.context[ke]?.onGenuine?.()},genuine(){if(!C(V))return null;let X=[...V.waiters].find(de=>de.pendingTerminal&&ve(de.context)?.key===V.key);return X&&V.genuineAt!==null?{at:V.genuineAt,context:X.context}:null},promote(){clearTimeout(Y)},finish:X=>Q(X),cancel(){E.abort(),clearTimeout(Y);try{j?.abort(),j?.destroy()}catch{}}};b=V,_.set(V.key,V),Y=setTimeout(()=>te(V),Yi),(async()=>{try{let X=await t(y.context,E.signal);if(E.signal.aborted||p||R!==m||!C(V)||!l())return null;if(!X||!Number.isSafeInteger(X.size)||X.size<1||X.size>Fe)return x.rejected++,null;for(;!D(X.size)&&k.size&&h.state!=="buffering";)z(k.keys().next().value);if(!D(X.size))return x.rejected++,null;if(V.reserved=X.size,!s(M()))return V.reserved=0,x.rejected++,null;x.highWaterBytes=Math.max(x.highWaterBytes,x.cacheBytes+M());let de=y.context[ke]={peerBytes:0,genuine:()=>V.genuine(),startupDependency:()=>{if(!Z()||!C(V)||!l()||!Dt(y))return null;try{return et()===null||!Z()?null:{at:h.entryAt,deadline:h.deadline,signal:h.controller.signal,context:y.context}}catch{return null}}};j=new n(q),x.started++;let J=performance.now(),re=await new Promise(ie=>j.load(y.context,L,{onSuccess:(me,he,Ne,Le)=>ie({response:me,stats:he,details:Le,serviceMs:ll(he,X.size,J,performance.now())}),onError:(...me)=>ie({failure:{name:"onError",args:me,stats:j.stats}}),onTimeout:(...me)=>ie({failure:{name:"onTimeout",args:me,stats:j.stats}}),onAbort:(...me)=>ie({failure:{name:"onAbort",args:me,stats:j.stats}}),onProgress:me=>{if(me?.loaded>X.size){E.abort();try{j.abort()}catch{}ie(null)}}}));if(re?.failure)return E.signal.aborted||p||R!==m||!C(V)?null:(x.rejected++,re);if(!re||E.signal.aborted||p||R!==m||!C(V)||!await r(X,re.response.data,y.context,E.signal))return x.rejected++,null;if(E.signal.aborted||p||R!==m||!C(V))return null;let le=re.response.data;if(le.byteLength!==X.size)return x.rejected++,null;if(V.reserved=0,i?.(X,le,y.context)===!1)return null;let pe={...re,context:y.context,scope:y.scope,data:le,permit:X,peerBytes:de.peerBytes,accept:de.accept};return k.set(y.key,pe),x.cacheBytes+=le.byteLength,x.verified++,x.verifiedBytes+=le.byteLength,x.verifiedPeerBytes+=de.peerBytes,Z()&&C(V)&&m===R&&y.scope===v&&Dt(y)&&(h.planningServiceMs=re.serviceMs),pe}catch{return E.signal.aborted||x.rejected++,null}finally{clearTimeout(Y);try{j?.destroy()}catch{}}})().then(X=>ee(V,X))},ue=(y,E,R,q)=>{K=null;let L=ve(y);if(!L||p)return null;v!==L.scope&&(v!==null&&$(),v=L.scope),T=E,O=R;let j=[];try{j=e(y).map(ve).filter(Boolean).filter(Q=>Q.scope===v).slice(0,2)}catch{}let Y=new Set([L.key,...j.map(Q=>Q.key)]);for(let Q of k.keys())Y.has(Q)||z(Q);for(let Q of[..._.values()])Y.has(Q.key)||te(Q);return w=j,ft(L)&&j.every(ft)&&(K={own:Ie(L),upcoming:j.map(Ie),owner:q}),L},Z=()=>{if(h.state!=="buffering"||p||h.revision!==m||h.owner?.pendingTerminal!==h.terminal||h.terminal.settled)return!1;let y=!1;try{y=dt(ve(h.terminal.context),h.identity)&&dt(ve(h.own.context),h.identity)&&h.terminal.context.url===h.contextUrl&&h.terminal.context.frag.url===h.fragUrl}catch{}return y?!0:(se("cancelled","context-changed"),!1)},oe=y=>({code:0,text:"RelaySwarm startup buffer unavailable",startupBufferReason:y}),ge=y=>e(y.context).map(ve).filter(Boolean).filter(E=>E.scope===v&&ft(E)).slice(0,2),Ie=y=>{let{key:E,scope:R,context:{url:q,frag:L}}=ve(y.context);return{key:E,scope:R,context:{url:q,frag:L,part:null,responseType:"arraybuffer"}}},Ke=(y,E)=>({...Ie(y),identity:Ie(y),parent:Ie(E)}),Ee=y=>{try{return dt(ve(y.context),y.identity)&&ge(y.parent).some(E=>dt(E,y.identity))}catch{return!1}},Dt=y=>{if(!Z()||K?.owner!==h.terminal.id)return!1;let E=h.plan.find(R=>dt(R.identity,y));return!!(E&&Ee(E))},se=(y,E,R=!0)=>{if(!["idle","buffering"].includes(h.state))return;let q=h.owner,L=h.terminal;h.state=y,h.reason=E,y==="failed"&&h.failures++,y==="cancelled"&&h.cancellations++,clearTimeout(h.timer),h.timer=null,clearTimeout(h.poll),h.poll=null,h.controller?.abort(),h.releasePins?.(),h.owner=null,h.terminal=null,h.response=null,h.reserved=0,w=[],h.plan=[],h.cursor=null,h.frozenStart=null,h.planningServiceMs=null;for(let j of[..._.values()])te(j);for(let j of k.keys())z(j);if(!(!q||!L||L.settled||q.pendingTerminal!==L)){L.settled=!0,q.pendingTerminal=null,q.token++,q.stats.aborted=!0;try{q.inner.abort()}catch{}!R||p||(y==="cancelled"?L.callbacks.onAbort?.(q.stats,L.context,null):L.callbacks.onError?.(oe(E),L.context,null,q.stats))}},et=()=>{let y;try{y=u()}catch{return se("failed","target-threw"),null}return y===null?(se("cancelled","target-unavailable"),null):!Number.isFinite(y)||y<0?(se("failed","invalid-target"),null):(h.targetTime=y,y)},St=()=>{let y;try{y=g(h.own.context)}catch{}return!Number.isFinite(y)||y<0?(se("failed","invalid-recovery"),null):(h.requiredHeadroomMs=y,y)},Et=(y,E)=>{if(!Z()||h.checking)return;if(h.frozenStart!==null&&y>=h.frozenStart&&(h.frozenStart=null),h.plan.some(L=>!Ee(L))||h.cursor&&!Ee(h.cursor))return se("cancelled","context-changed");for(;h.plan.length;){let L=h.plan[0],j=k.get(L.key),Y=_.get(L.key);if(L.context.frag.start+L.context.frag.duration>y||Y||j&&N.has(j.permit.key)||[...W].some(Q=>Q.pendingTerminal&&ve(Q.context)?.key===L.key))break;if(!j){if(!h.hopAvailable)return;h.hopAvailable=!1}if(h.cursor=L,h.plan.shift(),w=w.filter(Q=>Q.key!==L.key),!Z()||h.checking)return;z(L.key)}let R=2;if(h.verified&&h.response&&h.plan.length===2&&k.size===2&&!b&&!_.size&&!W.size&&!F.size&&h.plan.every(L=>k.has(L.key)&&!N.has(k.get(L.key).permit.key))){let L=tt(y);L.end!==null&&h.plan.every(j=>L.rows.includes(k.get(j.key)))&&(L.end-y)*1e3k.has(L.key)&&!N.has(k.get(L.key).permit.key))){let L=tt(y);L.end!==null&&(L.end-y)*1e3L.context.frag.start)?h.cursor:L??h.own,Y;try{Y=ge(j)[0]}catch{return se("cancelled","context-changed")}if(!Y)return;let Q=j.context.frag.start+j.context.frag.duration;if(Math.abs(Y.context.frag.start-Q)>.001||Y.key===h.own.key||h.plan.some(X=>X.key===Y.key))return se("cancelled","context-changed");let V=Ke(Y,j);if(Y.context.frag.start+Y.context.frag.duration<=y){if(!h.hopAvailable)return;h.hopAvailable=!1,h.cursor=V;return}h.plan.push(V),w.push(Y)}},Ut=()=>{if(!Z()||h.checking)return!1;let y=et();if(y===null||!Z())return!1;let E=St();if(E===null||!Z()||(Et(y,E),!Z()||h.checking||!w.length))return!1;if(h.frozenStart!==null&&yy)return!0;let R=w[0],q=h.plan.findIndex(L=>L.key===R.key);if(q<0)return se("cancelled","context-changed"),!1;if(h.verified){let L=tt(y);if(L.end!==null&&L.rows.filter(j=>j.context!==h.own.context).length>=2&&Math.abs(R.context.frag.start-L.end)<=.001)return!0}if(R.context.frag.start+R.context.frag.duration<=y+(E+(h.planningServiceMs??0))/1e3){if(!h.hopAvailable)return!1;h.hopAvailable=!1,h.cursor=h.plan[q],h.plan.splice(q,1),w.shift(),Et(y,E);let L=w[0]?.context.frag.start;return L>y&&(h.frozenStart=L),!1}return!0},Re=()=>{if(h.poll!==null||!Z())return;let y=h.deadline-performance.now();if(y<=0)return se("failed","deadline");h.poll=setTimeout(()=>{if(h.poll=null,!!Z()){if(!h.checking){h.hopAvailable=!0;let E=et();if(E===null||!Z())return;if(!l())return se("cancelled","not-allowed");let R=St();if(R===null||!Z()||(Et(E,R),!Z()))return;Ve(E),queueMicrotask(ne)}Re()}},Math.min(al,y))},tt=(y,E=null)=>{let R=h.verified&&h.response?[{...h.own,permit:h.permit}]:[],q=(E??[...R,...k.values()]).filter(Q=>Q.scope===v&&ft(Q)).sort((Q,V)=>Q.context.frag.start-V.context.frag.start),L=null,j=null,Y=[];for(let Q of q){let V=Q.context.frag.start,X=V+Q.context.frag.duration;L===null?V<=y&&yj&&(j=X,Y.push(Q))}return h.verifiedStart=L,h.verifiedEnd=j,{start:L,end:j,rows:Y}},Ce=(y=void 0)=>{if(!Z())return null;if(y===void 0&&(y=et()),y===null||!Z())return;if(!l())return se("cancelled","not-allowed");let E;try{E=g(h.own.context)}catch{}if(!Number.isFinite(E)||E<0)return se("failed","invalid-recovery");h.requiredHeadroomMs=E;let R=tt(y);if(!(R.end===null||(R.end-y)*1e3new Promise((E,R)=>{let q=!1,L=Y=>{q||(q=!0,y.removeEventListener("abort",j),Y?E():R(null))},j=()=>L(!1);if(y.addEventListener("abort",j,{once:!0}),y.aborted)return j();try{Promise.resolve(d(Object.freeze({signal:y}))).then(()=>L(!0),()=>L(!1))}catch{L(!1)}}),Ve=async(y=void 0)=>{if(!Z()||h.checking||!h.verified)return;let E=Ce(y);if(!E)return;h.checking=!0;let R=h.owner,q=h.terminal,L=m,j=new Map,Y=[],Q=!0,V=()=>{if(Q){Q=!1;for(let J of Y){let re=(N.get(J)??0)-1;re>0?N.set(J,re):N.delete(J)}h.releasePins===V&&(h.releasePins=null)}};h.releasePins=V;let X=()=>[...j.values()].some(({key:J,row:re,identity:le})=>k.get(J)!==re||!dt(ve(re.context),le)||re.data.byteLength!==re.permit.size)?(se("failed","coverage-evicted"),!1):[...j.values()].some(({key:J,row:re})=>!Dt({key:J,scope:re.scope,context:re.context}))?(se("cancelled","context-changed"),!1):!0,de=async({covered:J})=>{for(let[pe,ie]of k)J.rows.includes(ie)&&!j.has(ie)&&(j.set(ie,{key:pe,row:ie,identity:ve(ie.context)}),Y.push(ie.permit.key),N.set(ie.permit.key,(N.get(ie.permit.key)??0)+1));let re=[{context:h.own.context,permit:h.permit},...J.rows.filter(pe=>pe.context!==h.own.context)],le=await Promise.all(re.map(pe=>t(pe.context,h.controller.signal)));return()=>{if(!Z()||m!==L)return;if(le.some((he,Ne)=>!he||he.key!==re[Ne].permit.key||he.size!==re[Ne].permit.size||he.sha256!==re[Ne].permit.sha256))return se("failed","authority-changed");let pe=et();if(pe===null||!Z())return;if(!l())return se("cancelled","not-allowed");let ie;try{ie=g(h.own.context)}catch{}if(!Number.isFinite(ie)||ie<0)return se("failed","invalid-recovery");if(h.requiredHeadroomMs=ie,le.some((he,Ne)=>typeof he.current!="function"||he.current(re[Ne].context)!==!0))return se("failed","authority-changed");if(!Z())return;if(performance.now()>=h.deadline)return se("failed","deadline");if(!X())return;let me=tt(pe,J.rows);if(!(me.end===null||(me.end-pe)*1e3=h.deadline)return se("failed","deadline");if(h.commitCompleted=!0,!X())return;let ie=Ce();if(!ie||(J=await de(ie),!J()))return}let re=h.response,le=q.context[ke];if(o?.(q.context,re[0].data.byteLength,le?.peerBytes??0),!Z())return;if(!l())return se("cancelled","not-allowed");if((le?.commit??le?.accept)?.(q.context),!Z())return;le?.peerBytes>0&&(x.consumedPeerBytes+=le.peerBytes),h.state="ready",h.reason=null,h.released++,h.planningServiceMs=null,clearTimeout(h.timer),h.timer=null,clearTimeout(h.poll),h.poll=null,h.reserved=0;let pe=h.controller;if(h.owner=null,h.terminal=null,h.response=null,h.plan=[],h.cursor=null,h.frozenStart=null,!c){w=[];for(let ie of[..._.values()])te(ie)}try{R.deliver(q,"onSuccess",re)}finally{try{pe.abort()}finally{le?.notify?.()}}}catch{Z()&&se("failed","authority-refused")}finally{V(),h.checking=!1,h.state==="buffering"&&(queueMicrotask(ne),h.recheck&&(h.recheck=!1,queueMicrotask(Ve)))}},Yr=(y,E,R,q)=>{if(!h.enabled)return!0;if(h.state==="failed"||h.state==="cancelled")return h.state==="cancelled"&&(y.stats.aborted=!0),y.deliver(E,h.state==="cancelled"?"onAbort":"onError",h.state==="cancelled"?[y.stats,E.context,null]:[oe(h.reason),E.context,null,y.stats]),!1;if(!R)return h.state==="idle"&&E.context.frag?.type==="main"&&E.context.frag.sn!=="initSegment"?(h.state="failed",h.reason="unsupported-context",h.failures++,y.deliver(E,"onError",[oe(h.reason),E.context,null,y.stats]),!1):!0;if(h.state==="buffering")return se("cancelled","superseded"),y.deliver(E,"onAbort",[y.stats,E.context,null]),!1;if(h.state!=="idle")return!0;let L=performance.now(),j=q?.loadPolicy?.maxLoadTimeMs??q?.timeout;if(Object.assign(h,{state:"buffering",owner:y,terminal:E,own:R,revision:m,reserved:f,entryAt:L,identity:{key:R.key,scope:R.scope,context:{frag:{start:R.context.frag.start,duration:R.context.frag.duration}}},contextUrl:E.context.url,fragUrl:E.context.frag.url,controller:new AbortController,deadline:L+Math.min(qr,Number.isFinite(j)&&j>0?j:qr)}),h.plan=(K?.upcoming??[]).map(Y=>Ke(Y,R)),K?.owner===E.id&&(K.rolling=h.plan),h.cursor=null,E.context[ke]={peerBytes:0,genuine:()=>Z()?{at:L,context:E.context}:null},!ft(R)||!l())return se("failed","not-allowed"),!1;if(y.config.progressive===!0)return se("failed","progressive-unsupported"),!1;if(et()===null||!Z())return!1;try{if(!s(M()))return se("failed","reservation-refused"),!1}catch{return se("failed","reservation-refused"),!1}return Z()?l()?(h.timer=setTimeout(()=>se("failed","deadline"),Math.max(0,h.deadline-performance.now())),Re(),Promise.resolve().then(()=>Z()?t(R.context,h.controller.signal):null).then(Y=>{if(Z()){if(!Y||!Number.isSafeInteger(Y.size)||Y.size<1||Y.size>Fe)return se("failed","first-authority-refused");if(h.permit=Y,h.reserved=Y.size,!s(M()))return se("failed","reservation-refused");x.highWaterBytes=Math.max(x.highWaterBytes,x.cacheBytes+M()),ir(),queueMicrotask(ne)}}).catch(()=>{Z()&&se("failed","first-authority-refused")}),!0):(se("cancelled","not-allowed"),!1):!1},ir=async()=>{if(!(!Z()||!h.response||!h.permit||h.verifying||h.verified)){h.verifying=!0;try{let y=h.response[0].data,E=h.permit;if(!(y instanceof ArrayBuffer)||y.byteLength!==E.size||!await r(E,y,h.own.context,h.controller.signal))return Z()&&se("failed","first-integrity");if(!Z())return;h.verified=!0,x.verified++,x.verifiedBytes+=y.byteLength,x.verifiedPeerBytes+=h.terminal.context[ke]?.peerBytes??0,Ve()}catch{Z()&&se("failed","first-integrity")}finally{h.verifying=!1}}};return{Loader:class{static relayswarmShadow=!0;constructor(E){this.config=E,this.inner=new n(E),this.stats=this.inner.stats,this.context=null,this.token=0}load(E,R,q){this.abort(),this.context=E;let L={id:++A,context:E,callbacks:{...q},settled:!1};this.pendingTerminal=L,q={...q};for(let de of["onSuccess","onError","onTimeout","onAbort"])q[de]=(...J)=>this.complete(L,de,J);let j=++this.token,Y=ue(E,this.config,R,L.id),Q=Y&&k.get(Y.key);if(!Yr(this,L,Y,R))return;let V=!Q&&Y&&_.get(Y.key),X=Q??V?.promise;if(X){V&&(x.coalesced++,V.waiters.add(this),this.warmPending=V,V.noteDemand(),b===V&&F.size===0&&(b=null,F.add(V),V.promote(),x.promotions++)),this.reuseAbort=new AbortController;let de=m,J=null,re,le=null,pe=()=>j===this.token,ie=()=>{if(clearTimeout(re),P.delete(me),le!==null){let he=N.get(le)-1;he>0?N.set(le,he):N.delete(le),le=null}},me=(he=!1)=>{if(he&&(ie(),this.reuseAbort.abort()),!pe()||J||this.originStarted)return;this.originStarted=!0,clearTimeout(re);let Ne={...q,onProgress:(...Le)=>{!pe()||J==="cache"||(Le[2]?.byteLength>0&&(J="origin",this.reuseAbort.abort(),ie()),q.onProgress?.(...Le))}};for(let Le of["onSuccess","onError","onTimeout","onAbort"])Ne[Le]=(...zt)=>{!pe()||J==="cache"||(J="origin",this.reuseAbort.abort(),ie(),q[Le]?.(...zt))};this.start(E,R,Ne,j)};this.cancelReuse=()=>{ie(),this.reuseAbort.abort()},P.add(me),Promise.resolve(X).then(async he=>{if(!pe())return;if(this.releasePending(),p||!he||de!==m)return me(!0);if(he.failure){let{name:ts,args:Xr,stats:rs}=he.failure;J="origin",ie(),this.reuseAbort.abort(),rs&&Object.assign(this.stats,rs),ts==="onError"?q.onError(Xr[0],E,Xr[2],this.stats):q[ts](this.stats,E,Xr[2]);return}le=he.permit.key,N.set(le,(N.get(le)??0)+1);let Ne=Math.max(0,Math.min(25,a(E)||0));Ne>0?re=setTimeout(me,Ne):me();let Le;try{Le=await t(E,this.reuseAbort.signal)}catch{}if(!pe()||J==="origin")return;if(p||de!==m)return me(!0);if(!Le||Le.key!==he.permit.key||Le.size!==he.permit.size||Le.sha256!==he.permit.sha256)return z(Y.key),me();J="cache",ie(),this.originStarted&&this.inner.abort(),Object.assign(this.stats,he.stats);let zt=he.data.slice(0);x.localReuseBytes+=zt.byteLength,he.accepted||(he.accepted=!0,he.accept?.(E),x.consumedPeerBytes+=he.peerBytes),o?.(E,zt.byteLength,he.peerBytes),q.onSuccess({...he.response,data:zt},this.stats,E,he.details),queueMicrotask(ne)})}else this.start(E,R,q,j);queueMicrotask(ne)}start(E,R,q,L){W.add(this),W.size+F.size>1&&b&&te(b);let j=this.pendingTerminal,Y=()=>{W.delete(this),queueMicrotask(ne)},Q={...q};Q.onProgress=(...V)=>{if(!(p||L!==this.token||!j||j.settled||this.pendingTerminal!==j)){if(h.owner===this&&(V[0]?.loaded>(h.permit?.size??Fe)||V[2]?.byteLength>(h.permit?.size??Fe)))return se("failed","first-oversize");if(h.owner===this&&V[2]!==null&&V[2]!==void 0){Z();return}q.onProgress?.(...V)}};for(let V of["onSuccess","onError","onTimeout","onAbort"])Q[V]=(...X)=>{Y(),L===this.token&&q[V]?.(...X)};this.inner.load(E,R,Q)}releasePending(){let E=this.warmPending;this.warmPending=null,E&&(E.waiters.delete(this),E.waiters.size||E.context[ke]?.onGenuine?.(),F.has(E)&&!E.waiters.size&&te(E))}complete(E,R,q){if(!(!E||E.settled||this.pendingTerminal!==E)){if(h.owner===this&&h.terminal===E&&h.state==="buffering"){if(R==="onSuccess"){let L=q[0]?.data;if(!(L instanceof ArrayBuffer)||L.byteLength>(h.permit?.size??Fe))return se("failed","first-oversize");h.response=q,ir();return}h.state=R==="onAbort"?"cancelled":"failed",h.reason=R==="onAbort"?"origin-abort":"origin-error",R==="onAbort"?h.cancellations++:h.failures++,clearTimeout(h.timer),clearTimeout(h.poll),h.poll=null,h.controller?.abort(),h.releasePins?.(),h.owner=null,h.terminal=null,h.response=null,h.reserved=0,w=[],h.plan=[],h.cursor=null,h.frozenStart=null,h.planningServiceMs=null;for(let L of[..._.values()])te(L);for(let L of k.keys())z(L)}this.deliver(E,R,q)}}deliver(E,R,q){!E||E.settled||this.pendingTerminal!==E||(R!=="onSuccess"&&K?.owner===E.id&&(K=null),E.settled=!0,this.pendingTerminal=null,E.callbacks[R]?.(...q))}cancel(E){let R=this.pendingTerminal;h.owner===this&&h.terminal===R&&se("cancelled","caller-abort",!E&&!p),R&&K?.owner===R.id&&(K=null),this.token++,this.originStarted=!1,this.cancelReuse?.(),this.releasePending(),W.delete(this),R&&(this.stats.aborted=!0),E&&R&&(R.settled=!0,this.pendingTerminal=null);try{E?this.inner.destroy():this.inner.abort()}finally{E||this.complete(R,"onAbort",[this.stats,R?.context,null])}}abort(){this.cancel(!1)}destroy(){this.cancel(!0)}getCacheAge(){return this.inner.getCacheAge?.()??null}getResponseHeader(E){return this.inner.getResponseHeader?.(E)??null}},clear:$,startupSnapshot:()=>({enabled:h.enabled,state:h.state,reason:h.reason,heldObjects:h.state==="buffering"?B():0,heldBytes:h.state==="buffering"?x.cacheBytes+M():0,targetTime:h.targetTime,verifiedStart:h.verifiedStart,verifiedEnd:h.verifiedEnd,requiredHeadroomMs:h.requiredHeadroomMs,planningServiceMs:h.planningServiceMs,released:h.released,failures:h.failures,cancellations:h.cancellations,commitStarted:h.commitStarted,commitCompleted:h.commitCompleted,limits:{objects:Yn,bytes:f,futureBytes:Fe,deadlineMs:qr}}),contains(y){if(p||!l()||!Number.isFinite(y))return!1;for(let R of[..._.values(),...k.values()])if(R.scope===v&&Zn(R,y))return!0;let E=K;if(!E||E.own.scope!==v||!Zn(E.own,y))return!1;try{let R=E.rolling??e(E.own.context).map(ve).filter(Boolean).filter(L=>L.scope===v).slice(0,2),q=new Map([E.own,...R].map(L=>[L.key,L]));return(E.rolling?R.some(L=>!Ee(L)):R.length!==E.upcoming.length||R.some((L,j)=>!dt(L,E.upcoming[j])))||[..._,...k].some(([L,j])=>!dt({...j,key:L},q.get(L)))?(K=null,!1):!0}catch{K=null}return!1},pinned:y=>N.has(y),release(y){for(let[E,R]of k)R.permit.key===y&&z(E)},stop(){p=!0,$()},snapshot:()=>({...x,reservationBytes:M(),active:+!!b,promoted:F.size,trackedObjects:B(),queued:w.length,cacheObjects:k.size,limits:{objects:U(),bytes:H(),speculativeWholeRequests:1,deadlineMs:h.state==="buffering"?qr:Yi,revalidationMs:25}})}}function Ji({now:n,take:e,give:t,delay:r,validate:s,refuse:i,maxWaiters:o}){let a=new Map,l=new Set,c={waited:0,waitTotalMs:0,waitMaxMs:0,granted:0,expired:0,cancelled:0,refused:0},u=!1,d=null,f=v=>{if(!v.waiting)return;let w=Math.max(0,n()-v.queuedAt);c.waited++,c.waitTotalMs+=w,c.waitMaxMs=Math.max(c.waitMaxMs,w)},g=(v,w)=>{a.get(v.link)===v&&(a.delete(v.link),f(v),c[w]++,i(w),v.resolve(null))},p=(v,w=!1)=>{l.delete(v)&&(v.active=!1,w||t(v.charge),queueMicrotask(m))},m=()=>{if(clearTimeout(d),d=null,!u)for(;a.size;){let v=a.values().next().value;if(n()>=v.deadline){g(v,"expired");continue}if(!s(v)){g(v,"cancelled");continue}if(!e(v.charge)){v.waiting=!0;let w=v.deadline-n();d=setTimeout(m,Math.max(1,Math.ceil(Math.min(w,r(v.charge)))));return}a.delete(v.link),f(v),v.active=!0,v.controller=new AbortController,l.add(v),c.granted++,v.resolve(v)}},b=v=>{for(let w of[...a.values()])(!v||w.link===v)&&g(w,"cancelled");for(let w of[...l])(!v||w.link===v)&&(c.cancelled++,w.controller.abort(),p(w));m()};return{acquire(v,w){return u||a.has(v)||[...l].some(T=>T.link===v)||a.size>=o||!w.range&&(a.size||r(w.charge)>0)?(c.refused++,i("refused"),Promise.resolve(null)):new Promise(T=>{let O=n();a.set(v,{link:v,key:w.key,size:w.size,charge:w.charge,range:w.range?{start:w.range.start,end:w.range.end}:null,queuedAt:O,deadline:O+250,resolve:T,waiting:a.size>0,active:!1}),m()})},finish:p,cancel:b,recheck:m,stop(){u=!0,b(),clearTimeout(d),d=null},snapshot:()=>({enabled:!0,...c,queued:a.size,reservedBytes:[...l].reduce((v,w)=>v+w.charge,0),limits:{waitMs:250,waiters:o,perLink:1}})}}var hl=2,jr="webrtc",Xn=16,Jn=3e4,ul=1e4,Wr=300,Kr=32*1024,Qi=Object.freeze({mode:"shadow",originFallbackMs:1500,maxPeerWaitMs:5e3,originReserveMs:2e3,sustainablePeerWait:!1,warmAhead:!1,startupBufferTarget:null,startupBufferMaxBytes:24*1024*1024,startupBufferCommit:null,lateWindowMs:6e3,maxPeers:6,maxUploadPeers:4,maxUploadBytesPerSecond:125e4,uploadPacing:!1,maxUploadBytesPerSession:void 0,maxDialsInFlight:2,dialTimeoutMs:12e3,presenceIntervalMs:2e4,metricsIntervalMs:1e4,maxHeldSegments:12,maxHeldBytes:64*1024*1024,maxSegmentBytes:16*1024*1024,shadowSampleRate:.25,maxConcurrentRaces:24,admissionTimeoutMs:3e3,swarmParts:!1,serveOnCellular:!1,serve:!1,ticket:void 0,admit:void 0,minLinkLifeMs:15e3,idleEvictMs:2e4,evictionCooldownMs:1e4,retryFloorMs:4e3,retryCeilingMs:45e3,maxRetriesPerPeer:3,maxReferrals:2,reannounceDebounceMs:4e3,minReannounceGapMs:12e3,iceServers:[{urls:"stun:stun.l.google.com:19302"}],iceTransportPolicy:"all",coreWasm:void 0,transferWorkerUrl:void 0,multiHolder:!1,zeroBudgetPeerRace:!1,lateHaveRace:!1,latePeerRace:!1,maxHoldersPerObject:3,traceRequests:0,abrIgnorePeers:!1,peerSupplyHint:!1,onPlayerHint:null,onPeerDelivery:null}),dl=32768,fl=500,pl=2e3,I=()=>performance.now(),Vr=n=>{let e=n?.loading?.first;return Date.now()-(Number.isFinite(e)&&e>0&&e<=I()?I()-e:0)},ao=n=>Array.from(new Uint8Array(n),e=>e.toString(16).padStart(2,"0")).join(""),eo=new TextEncoder;async function Pt(n){return ao(await globalThis.crypto.subtle.digest("SHA-256",n))}function to(n){return new URL(n,globalThis.location?.href).pathname}function gl(n){try{return new URL(n,globalThis.location?.href).origin}catch{return String(n)}}function Be(n,e){if(!n.length)return null;let t=[...n].sort((r,s)=>r-s);return Math.round(t[Math.min(t.length-1,Math.floor(e*t.length))])}function ml(n,e){if(!n.length)return null;let t=[...n].sort((r,s)=>r-s);return t[Math.min(t.length-1,Math.floor(e*t.length))]}function Qn(n){return{p50:Be(n,.5),p90:Be(n,.9)}}function We(n,e){n.push(e),n.length>fl&&n.shift()}function Ht(){let n=globalThis.navigator?.connection;return!!(n&&(n.type==="cellular"||n.saveData))}var $r=Object.freeze({created:["outgoing","incoming"],gathering:["new","gathering","complete","unknown"],ice:["new","checking","connected","completed","failed","disconnected","closed","unknown"],connection:["new","connecting","connected","disconnected","failed","closed","unknown"],"local-offer":["complete","capped","aborted","unknown"],"local-answer":["complete","capped","aborted","unknown"],"offer-received":["authenticated"],"answer-received":["authenticated"],"offer-admitted":["accepted"],"answer-admitted":["accepted"],"remote-installed":["offer","answer"],"signal-send":["offer","answer"],"signal-failed":["offer","answer"],"channel-open":["accepted","stale"],negotiation:["glare-yield"],"dial-end":["timeout","failed","rejected","superseded","admission","host-stop"],"link-close":["host","host-stop","admission","rotation","integrity","request-timeout","request-abort","native-failed","native-closed","native-disconnected","channel-close","channel-error","protocol","send-error","serve-error","upload-queue","upload-drain-timeout"]}),Oe=n=>Math.min(Number.MAX_SAFE_INTEGER,n+1),ro=Object.freeze(["no-budget","aborted-before-eligibility","no-have-no-wait","no-have-wait","wait-no-longer-eligible","wait-aborted","wait-expired","have-at-entry","have-after-wait","projected-late"]),no=Object.freeze(["payload","none","timeout","abort","abandoned","closed","busy","send-error"]),yl=15e3,bl=250,wl=50,so=Object.freeze(["presence","dialStart","offerBeforeSend","offerIncoming","answerIncoming","glareBeforeRollback","glareAfterRollback","answerBeforeSend","upload","refresh","other"]),vl=Object.freeze(["admission","not-held","not-serving","banned","session-allowance","peer-limit","rate-limit","reservation-refused","reservation-inactive"]);function io(n,e=1200,t,r){return new Promise(s=>{let i=c=>{try{r?.(c)}catch{}s(c)};if(n.iceGatheringState==="complete"||t?.aborted)return i(t?.aborted?"aborted":"complete");let o=()=>{clearTimeout(l),n.removeEventListener("icegatheringstatechange",a),t?.removeEventListener("abort",o);let c="unknown";try{c=t?.aborted?"aborted":n.iceGatheringState==="complete"?"complete":"capped"}catch{}i(c)},a=()=>{n.iceGatheringState==="complete"&&o()},l=setTimeout(o,e);n.addEventListener("icegatheringstatechange",a),t?.addEventListener("abort",o,{once:!0})})}async function xl(n){try{let e=await n.getStats(),t=null;return e.forEach(r=>{r.type==="transport"&&r.selectedCandidatePairId&&(t=e.get(r.selectedCandidatePairId)||t)}),t||e.forEach(r=>{r.type==="candidate-pair"&&r.state==="succeeded"&&(r.selected||r.nominated)&&(t=r)}),t?`${e.get(t.localCandidateId)?.candidateType||"?"}/${e.get(t.remoteCandidateId)?.candidateType||"?"}`:"unknown"}catch{return"unknown"}}function Sl(){return ao(globalThis.crypto.getRandomValues(new Uint8Array(12)))}function oo(n,{minLinkLifeMs:e,idleEvictMs:t,banned:r=new Set,tier:s}={},i=Date.now()){let o=null,a=0;for(let l of n){if(l.transferring||r.has(l.pubkey)||i-l.openedAttypeof i=="string"&&/^[0-9a-f]{64}$/u.test(i)).slice(0,e.maxReferrals):[];return{retryAfterMs:r,referrals:s}}function kl(n={}){let e=new es(n);return{attach:t=>e.attach(t),updateTicket:t=>e.updateTicket(t),stop:()=>e.stop(),metrics:()=>e.metrics(),peerConnections:()=>e.peerConnections(),peerConnectionDetails:()=>e.peerConnectionDetails(),trace:()=>e.trace()}}var es=class{constructor(e){this.options={...Qi,...e},this.options.iceTransportPolicy===void 0&&(this.options.iceTransportPolicy=Qi.iceTransportPolicy),this.startedAt=Date.now(),this.transportStartedAt=I(),this.transportSequence=0,this.transportRecords=[],this.transportDropped=0,this.transportCounters=Object.fromEntries(Object.entries($r).map(([t,r])=>[t,Object.fromEntries(r.map(s=>[s,0]))])),this.transportConnections=new WeakMap,this.peerEligibilityRecords=[],this.peerEligibilityDropped=0,this.peerEligibilityCounters=Object.fromEntries(ro.map(t=>[t,0])),this.holderLabels=new Map,this.traceRows=[],this.traceDropped=0,this.traceLoads=new WeakMap,this.traceLoadNext=1,this.traceBase=Math.floor(I()),this.holderLabelNext=1,this.peerRequestRecords=[],this.peerRequestDropped=0,this.peerRequestCounters=Object.fromEntries(no.map(t=>[t,0])),this.uploadRefusalCounters=Object.fromEntries(vl.map(t=>[t,0])),this.admissionCallCounters=Object.fromEntries(so.map(t=>[t,0])),this.disabledReason=this.#r(),this.stopped=!1,this.lifecycle=new AbortController,this.admissionChecks=new Map,this.dialChecks=new Set,this.hls=null,this.originalFragmentLoader=void 0,this.pool=null,this.session=null,this.timers=new Set,this.links=new Map,this.peerLeases=new Map,this.peerLeaseWaiters=new Set,this.peerAdmission={claims:0,waited:0,granted:0,expired:0,cancelled:0},this.latePeerOwners=new Map,this.latePeerGeneration=0,this.latePeerNextId=1,this.latePeerRows=[],this.latePeerDropped=0,this.latePeerCounts={entered:0,armed:0,won:0,expired:0,retired:0,refused:0},this.peerSelection=new wt,this.linkTimings=new WeakMap,this.core=null,this.coreVerifier=null,this.coreState="off",this.transferWorker=null,this.transferWorkerState=this.options.transferWorkerUrl===void 0?"off":"waiting-core",this.transferWorkerReason=null,this.coreWait=null,this.coreRelease=null,this.remoteFraming=new Map,this.transferIds=new WeakMap,this.nextTransferId=1,this.multiHolder={transfers:0,delivered:0,late:0,failed:0,bans:0,abandoned:0,peerBytes:0,originBytes:0,unusedBytes:0,originRanges:0,originRangesIgnored:0},this.peerFlow={verifiedShortBatches:0,verifiedShortBytes:0,lastVerifiedShortBatch:null,modelEvaluations:{fit:0,"useful-unknown":0,refresh:0,"cooldown-blocked":0,"known-slow":0},lastModel:null,noModelTransfers:0,lastNoModel:null},this.originRangeOutcomes=Object.fromEntries(["payload","invalid-request","wrong-size","error","timeout","abort","exception"].map(t=>[t,0])),this.originsWithoutRanges=new Set,this.multiHolderTimings=[],this.coreFallbacks=0,this.coreDecided={wasm:0,js:0},this.coreLinks={wasm:0,js:0},this.dials=new Map,this.receivedOffers=new Set,this.cooldowns=new Map,this.retries=new Map,this.openPeers=new Map,this.discovery=new _t,this.lastEvictionAt=0,this.lastAnnouncedAt=0,this.reannounceTimer=null,this.banned=new Set,this.admitted=new Map,this.held=new Map,this.heldBytes=0,this.races=new Set,this.cachedRaces=new Set,this.haveWaiters=new Set,this.rendition=null,this.renditions=new Map,this.originFetches=new Map,this.uploadQuotaBytes=0,this.uploadTokens=this.options.maxUploadBytesPerSecond,this.uploadRefilledAt=I(),this.uploadPacer=this.options.uploadPacing?Ji({now:I,maxWaiters:Math.min(this.options.maxUploadPeers,this.options.maxPeers),take:t=>(this.#Ee(),this.uploadTokens{this.uploadTokens=Math.min(this.options.maxUploadBytesPerSecond*2,this.uploadTokens+t)},delay:t=>(this.#Ee(),Math.max(0,(t-this.uploadTokens)*1e3/this.options.maxUploadBytesPerSecond)),validate:t=>this.#ke(t),refuse:t=>this.#y(t==="cancelled"?"not-serving":"rate-limit")}):null,this.playerHints=[],this.hintSizes=new Map,this.hintOriginRates=[],this.hintGeneration=0,this.peerFragments=new WeakSet,this.originalTrigger=null,this.counters={originLoaded:0,sampledOriginBytes:0,peerInTimeBytes:0,peerFirstLoaded:0,peerFirstBytes:0,zeroBudgetPeerRaces:0,zeroBudgetPeerRaceWins:0,abrPeerSamplesWithheld:0,originFallbacks:0,coordinatedWaits:0,coordinatedPeerLoads:0,peerSkippedLate:0,peerProjectedLate:0,peerWaitExtended:0,peerAbandoned:0,peerNoFit:0,peerUntestedTrial:0,peerUntestedTrialLoaded:0,commitmentRequests:0,commitmentRejected:0,commitmentUnavailable:0,raced:0,noPeers:0,sampledOut:0,skipped:0,peerInTime:0,peerLate:0,peerMiss:0,peerCorrupt:0,peerUnverified:0,aborted:0,bytesFromOrigin:0,bytesFromPeers:0,bytesUploaded:0,uploadsServed:0,uploadsRefused:0,uploadsCancelled:0,uploadCancelledBytes:0,dialsStarted:0,dialsAccepted:0,dialsFailed:0,dialsTimedOut:0,dialsRejected:0,offersAccepted:0,offersRefused:0,admitRefused:0,evicted:0,evictedUnhelpful:0,evictedServing:0,evictedConsumer:0,evictionsUnavailable:0,retriesScheduled:0,referralsSent:0,referralsFollowed:0,linksOpened:0,linksClosed:0,presenceSent:0,signalsSent:0,publishErrors:0,errors:0},this.firstLinkAtMs=null,this.firstPeerSegmentAtMs=null,this.pairTypes={},this.signallingSamples=[],this.originClockSamples=[],this.peerLatencySamples=[],this.originLatencySamples=[],this.renditionOriginSamples=new Map,this.renditionSizes=new Map,this.errorsByStage={}}#r(){let{swarmId:e,relays:t,mode:r}=this.options;if(typeof e!="string"||e.length<8||e.length>128)return"invalid-swarm-id";if(!Array.isArray(t)||t.length<1||t.length>8)return"invalid-relays";try{for(let o of t){let a=new URL(o);if(a.protocol!=="wss:"&&!(a.protocol==="ws:"&&["localhost","127.0.0.1","[::1]"].includes(a.hostname)))return"invalid-relays"}}catch{return"invalid-relays"}if(!["all","relay"].includes(this.options.iceTransportPolicy))return"invalid-ice-transport-policy";if(r==="off")return"mode-off";if(r!=="shadow"&&r!=="peer-first")return"invalid-mode";if(r==="peer-first"&&!Hr(this.options.streamEvent))return"invalid-stream-authorisation";if(r==="peer-first"&&typeof this.options.getCommitment!="function")return"missing-commitment-provider";let s=this.options.coreWasm;if(s!==void 0&&!(typeof s=="string"||s instanceof URL||s instanceof ArrayBuffer||ArrayBuffer.isView(s)||typeof WebAssembly=="object"&&s instanceof WebAssembly.Module))return"invalid-core-wasm";if(typeof this.options.multiHolder!="boolean"||!Number.isSafeInteger(this.options.maxHoldersPerObject)||this.options.maxHoldersPerObject<1||this.options.maxHoldersPerObject>8)return"invalid-multi-holder";let i=this.options.transferWorkerUrl;if(i!==void 0&&(r!=="peer-first"||!this.options.multiHolder||s===void 0||!(i instanceof URL||typeof i=="string"&&i.length>0&&i.length<=2048))||this.options.WorkerImpl!==void 0&&typeof this.options.WorkerImpl!="function")return"invalid-transfer-worker";if(!Number.isSafeInteger(this.options.traceRequests)||this.options.traceRequests<0||this.options.traceRequests>dl)return"invalid-trace";if(typeof this.options.peerSupplyHint!="boolean"||this.options.onPlayerHint!==null&&typeof this.options.onPlayerHint!="function")return"invalid-player-hint-option";if(typeof this.options.abrIgnorePeers!="boolean")return"invalid-abr-option";if(typeof this.options.zeroBudgetPeerRace!="boolean")return"invalid-cached-race-option";if(typeof this.options.lateHaveRace!="boolean")return"invalid-late-have-race-option";if(typeof this.options.latePeerRace!="boolean"||this.options.latePeerRace&&(r!=="peer-first"||!this.options.zeroBudgetPeerRace))return"invalid-late-peer-race-option";if(typeof this.options.sustainablePeerWait!="boolean")return"invalid-sustainable-wait-option";if(typeof this.options.warmAhead!="boolean"||this.options.warmAhead&&(r!=="peer-first"||this.options.serve!==!0))return"invalid-warm-ahead-option";if(this.options.startupBufferTarget!==null&&(typeof this.options.startupBufferTarget!="function"||r!=="peer-first"||this.options.serve!==!0))return"invalid-startup-buffer-target";if(!Number.isSafeInteger(this.options.startupBufferMaxBytes)||this.options.startupBufferMaxBytes<24*1024*1024||this.options.startupBufferMaxBytes>32*1024*1024||this.options.startupBufferMaxBytes!==24*1024*1024&&typeof this.options.startupBufferTarget!="function")return"invalid-startup-buffer-max-bytes";if(this.options.startupBufferCommit!==null&&(typeof this.options.startupBufferCommit!="function"||typeof this.options.startupBufferTarget!="function"))return"invalid-startup-buffer-commit";if(this.options.admit!==void 0&&typeof this.options.admit!="function")return"invalid-admit";if(this.options.reserveUploadBytes!==void 0&&typeof this.options.reserveUploadBytes!="function")return"invalid-upload-reservation";if(typeof this.options.serve!="boolean"||typeof this.options.serveOnCellular!="boolean")return"invalid-serve-option";if(typeof this.options.uploadPacing!="boolean")return"invalid-upload-pacing";if(this.options.ticket!==void 0&&!ye(this.options.ticket))return"invalid-ticket";if(this.options.maxUploadBytesPerSession!==void 0&&(!Number.isSafeInteger(this.options.maxUploadBytesPerSession)||this.options.maxUploadBytesPerSession<0))return"invalid-upload-session-limit";for(let o of["originFallbackMs","maxPeerWaitMs","originReserveMs","lateWindowMs","maxPeers","maxUploadPeers","maxUploadBytesPerSecond","maxDialsInFlight","dialTimeoutMs","presenceIntervalMs","metricsIntervalMs","maxHeldSegments","maxHeldBytes","maxSegmentBytes","maxConcurrentRaces","admissionTimeoutMs"])if(!Number.isSafeInteger(this.options[o])||this.options[o]<1)return"invalid-limits";return!Number.isFinite(this.options.shadowSampleRate)||this.options.shadowSampleRate<0||this.options.shadowSampleRate>1?"invalid-sample-rate":globalThis.crypto?.subtle?typeof(this.options.RTCPeerConnectionImpl||globalThis.RTCPeerConnection)!="function"?"no-webrtc":typeof(this.options.WebSocketImpl||globalThis.WebSocket)!="function"?"no-websocket":"":"no-webcrypto"}attach(e){if(!(this.stopped||this.hls||this.disabledReason||!e?.config))try{this.hls=e,this.originalFragmentLoader=e.config.fLoader;let t=e.config.fLoader||e.config.loader;if(e.config.fLoader=this.options.mode==="peer-first"?this.#b(t):this.#Qe(t),this.options.warmAhead||this.options.startupBufferTarget){this.warmAhead=Xi({Loader:e.config.fLoader,steady:this.options.warmAhead,startupTarget:this.options.startupBufferTarget,startupCommit:this.options.startupBufferCommit,startupMaxBytes:this.options.startupBufferMaxBytes,startupRecovery:i=>Math.max(this.options.originReserveMs,(Be(this.#W(i),.9)||0)*1.25+100),allowed:()=>this.#p()&&e.media?.paused!==!0&&!Ht(),next:i=>{let o=e.levels?.[i.frag?.level]?.details?.fragments;if(!Array.isArray(o))return[];let a=o.findIndex(l=>l.sn===i.frag.sn&&(l.cc??0)===(i.frag.cc??0));return a<0?[]:o.slice(a+1,a+3).map(l=>({url:l.url,frag:l,type:"media-fragment",headers:{},part:null,responseType:"arraybuffer",rangeStart:l.byteRangeStartOffset,rangeEnd:l.byteRangeEndOffset}))},authorise:async(i,o)=>{let a=await this.#C(i),l=await lt(d=>this.options.getCommitment(i,{signal:d}),o,1e3);if(o.aborted||this.stopped)return null;let c=d=>!this.stopped&&this.#ce(l,{streamEvent:this.options.streamEvent,swarmId:this.options.swarmId,key:a,context:d,maxSegmentBytes:this.options.maxSegmentBytes,delegation:this.options.delegation,revokedDelegationIds:this.options.revokedDelegationIds,delegationRevocations:this.options.delegationRevocations}),u=c(i);return u&&u.size<=this.options.maxHeldBytes?{...u,key:a,current:d=>{let f=c(d);return!!(f&&f.size===u.size&&f.sha256===u.sha256)}}:null},verify:async(i,o,a,l)=>o instanceof ArrayBuffer&&o.byteLength===i.size&&!l.aborted&&await Pt(o)===i.sha256,reserve:i=>(this.#ve(this.options.maxHeldBytes-i),!this.stopped&&this.heldBytes+i<=this.options.maxHeldBytes),reuseBudget:i=>{try{let o=e.media,a=o.currentTime,l=Math.max(this.options.originReserveMs,(Be(this.#W(i),.9)||0)*1.25+100);for(let c=0;ca)return Math.min(25,Math.max(0,(u-a)*1e3-l))}}catch{}return 0},onVerified:(i,o)=>(this.#nt(i.key),this.#L(i.key,new Uint8Array(o)),this.held.has(i.key)),onReuse:(i,o,a)=>{a>0&&i.frag&&this.peerFragments.add(i.frag)}}),e.config.fLoader=this.warmAhead.Loader;let r=e.media,s=()=>this.warmAhead?.clear();for(let i of["pause","ended"])r?.addEventListener?.(i,s,{signal:this.lifecycle.signal});r?.addEventListener?.("seeking",()=>{try{let i=r.currentTime;for(let o=0;o{r=o}),i=this.#h(pl,r);this.coreRelease=r,this.coreWait=s.then(()=>{clearTimeout(i),this.timers.delete(i),this.coreWait=null,this.coreRelease=null}),this.#n("core",()=>this.#ot().finally(r))}this.#n("start",()=>this.#ct()),typeof this.options.onMetrics=="function"&&this.#M(this.options.metricsIntervalMs,0,()=>this.options.onMetrics(this.metrics()))}catch(t){this.#o("attach",t)}}#t(e){let t=this,r=e.trigger;typeof r=="function"&&(this.originalTrigger=r,this.triggerWasOwn=Object.hasOwn(e,"trigger"),this.withheldTrigger=function(s,i){let o=(s==="hlsFragLoaded"||s==="hlsFragBuffered")&&i?.frag&&t.peerFragments.has(i.frag)?e.abrController?.bwEstimator:null;if(!o||typeof o.sample!="function"||typeof o.sampleTTFB!="function")return r.call(this,s,i);let a=()=>{t.counters.abrPeerSamplesWithheld+=1},l=["sample","sampleTTFB"].map(c=>[c,Object.getOwnPropertyDescriptor(o,c)]);o.sample=a,o.sampleTTFB=a;try{return r.call(this,s,i)}finally{for(let[c,u]of l)u?Object.defineProperty(o,c,u):delete o[c]}},e.trigger=this.withheldTrigger)}updateTicket(e){return this.stopped||this.disabledReason||!this.#G()||!ye(e)?!1:(e===this.options.ticket||(this.latePeerGeneration++,this.#a("ticket"),this.warmAhead?.clear(),this.options.ticket=e,this.#Be()),!0)}stop(){if(!this.stopped){this.stopped=!0,this.#a("stop"),this.uploadPacer?.stop(),this.warmAhead?.stop(),this.#q(),this.discovery.clear(),this.lifecycle.abort();for(let e of[...this.peerLeaseWaiters])e();this.peerLeases.clear(),this.transferWorker?.stop(),this.options.transferWorkerUrl!==void 0&&(this.transferWorkerState="stopped"),this.cachedRaces.clear(),this.admissionChecks.clear(),this.admitted.clear(),this.dialChecks.clear();for(let e of this.races)e.settled=!0,e.controller.abort();this.races.clear();try{this.hls&&this.hls.config.fLoader?.relayswarmShadow&&(this.hls.config.fLoader=this.originalFragmentLoader)}catch{}try{this.originalTrigger&&this.hls?.trigger===this.withheldTrigger&&(this.triggerWasOwn?this.hls.trigger=this.originalTrigger:delete this.hls.trigger)}catch{}this.originalTrigger=null;for(let e of this.timers)clearTimeout(e);this.timers.clear(),this.coreRelease?.();for(let e of this.haveWaiters)e();this.haveWaiters.clear();for(let e of this.dials.values()){this.#ie(e),this.#de(e.pc,"dial-end","host-stop");try{e.pc.close()}catch{}}this.dials.clear(),this.receivedOffers.clear();for(let e of[...this.links.values()])e.close("host-stop");this.links.clear(),this.held.clear(),this.heldBytes=0,this.originFetches.clear(),this.renditions.clear(),this.playerHints=[],this.hintSizes.clear(),this.hintOriginRates=[];try{this.session?.close()}catch{}try{this.pool?.close()}catch{}try{this.options.onMetrics?.(this.metrics())}catch{}}}trace(){return{v:1,capacity:this.options.traceRequests,dropped:this.traceDropped,rows:this.traceRows.map(e=>structuredClone(e))}}#e(e){if(this.options.traceRequests)try{this.traceRows.length>=this.options.traceRequests&&(this.traceRows.shift(),this.traceDropped=Oe(this.traceDropped)),this.traceRows.push(e)}catch{}}#s(e=I()){return Math.floor(e)-this.traceBase}#d(e){try{return(e&&this.traceLoads.get(e))??null}catch{return null}}#i(e,t,r,s){if(this.options.traceRequests)try{let i=this.traceLoadNext++;this.traceLoads.set(e,i);let o=a=>Number.isSafeInteger(a)?a:null;return this.#e({k:"load",load:i,at:this.#s(),sn:o(e.frag?.sn),level:o(e.frag?.level),cc:o(e.frag?.cc),budgetMs:Math.round(t),limitMs:Math.round(r),budgetGeometry:{...s}}),i}catch{}}#c(e,t,r){if(!this.options.traceRequests)return null;let s=I(),i=this.traceBase,o=!1,a=!1,l=!1,c=!1,u=g=>{let p=g;try{p??=r()}catch{}let m=b=>{try{let v=p?.[b];return Number.isSafeInteger(v)&&v>=0?v:null}catch{return null}};return{loaderLoadedBytes:m("loaded"),loaderTotalBytes:m("total")}},d=(g,p)=>this.#e({k:g,load:e,leg:t,at:this.#s(),ms:Math.round(I()-s),ranged:!1,...p});return d("originStart",{}),{progress:(g,p,m)=>{if(m){c||(c=!0,d("originCallback",{phase:"progress",outcome:null,stale:!0}));return}a||p!==!0||(a=!0,d("originProgress",{stale:!1,...u(g)}))},abortRequest:g=>{o||l||(l=!0,d("originAbortRequest",{reason:g,...u()}))},terminal:(g,p=null,m,b=!1)=>f(g,p,m,b)};function f(g,p,m,b){if(o){c||(c=!0,d("originCallback",{phase:"terminal",outcome:g,stale:!0}));return}o=!0;let v=b?{loaderLoadedBytes:null,loaderTotalBytes:null}:u(m);d("origin",{at:Math.floor(s)-i,outcome:g,bytes:Number.isSafeInteger(p)&&p>=0?p:null,stale:b,...v})}}peerConnections(){return this.peerConnectionDetails().map(e=>e.connection)}peerConnectionDetails(){let e=[];for(let t of this.links.values())try{!t.closed&&t.channel.readyState==="open"&&!["failed","closed","disconnected"].includes(t.pc.connectionState)&&e.push({connection:t.pc,pubkey:t.pubkey})}catch{}return e}metrics(){let e=this.counters,t=this.options.mode==="shadow",r=t?e.peerInTime+e.peerLate+e.peerMiss+e.peerCorrupt:0,s=r+e.noPeers,i=(o,a)=>a?Number((o/a).toFixed(3)):null;return{v:hl,swarmId:this.options.swarmId,mode:this.disabledReason?"off":this.options.mode,disabledReason:this.disabledReason||null,stopped:this.stopped,warmAhead:this.warmAhead?.snapshot()??null,startupBuffer:this.warmAhead?.startupSnapshot()??null,peerAdmission:{...this.peerAdmission,claimedLinks:this.peerLeases.size,waiting:this.peerLeaseWaiters.size},uploadPacing:this.uploadPacer?.snapshot()??null,latePeerRace:{enabled:this.options.latePeerRace,...this.latePeerCounts,pending:this.latePeerOwners.size,dropped:this.latePeerDropped,records:this.latePeerRows.map(o=>({...o,...o.holders?{holders:[...o.holders]}:{}})),limits:{windowMs:Math.min(4e3,this.options.lateWindowMs),peerMs:Math.min(2500,this.options.maxPeerWaitMs),owners:this.options.maxConcurrentRaces}},pubkey:this.session?.pubkey||null,uptimeMs:Date.now()-this.startedAt,serving:this.#p(),peers:{connected:this.links.size,dialling:this.dials.size,dialsStarted:e.dialsStarted,dialsAccepted:e.dialsAccepted,dialsFailed:e.dialsFailed,dialsTimedOut:e.dialsTimedOut,dialsRejected:e.dialsRejected,offersAccepted:e.offersAccepted,offersRefused:e.offersRefused,admitRefused:e.admitRefused,evicted:e.evicted,evictedUnhelpful:e.evictedUnhelpful,evictedServing:e.evictedServing,evictedConsumer:e.evictedConsumer,evictionsUnavailable:e.evictionsUnavailable,retriesScheduled:e.retriesScheduled,referralsSent:e.referralsSent,referralsFollowed:e.referralsFollowed,openPeersKnown:this.#_e().length,linksOpened:e.linksOpened,linksClosed:e.linksClosed,banned:this.banned.size,firstLinkAtMs:this.firstLinkAtMs,candidatePairs:{...this.pairTypes},deliveryMeasurements:[...this.links.values()].map(o=>({pubkey:o.pubkey,holder:this.#U(o.pubkey),...this.peerSelection.summary(o)}))},transportDiagnostics:{capacity:64,dropped:this.transportDropped,counters:Object.fromEntries(Object.entries(this.transportCounters).map(([o,a])=>[o,{...a}])),records:this.transportRecords.map(o=>({...o}))},neighbourDiscovery:this.discovery.snapshot(),...this.options.peerSupplyHint?{playerHint:structuredClone(this.playerHints)}:{},peerEligibilityDiagnostics:{capacity:64,dropped:this.peerEligibilityDropped,counters:{...this.peerEligibilityCounters},records:this.peerEligibilityRecords.map(o=>({...o,budgetGeometry:{...o.budgetGeometry},..."holders"in o?{holders:o.holders&&[...o.holders],haveHolders:o.haveHolders&&[...o.haveHolders],staleHolders:o.staleHolders&&[...o.staleHolders],heldMissHolders:o.heldMissHolders&&[...o.heldMissHolders]}:{},...o.projection?{projection:{...o.projection}}:{}}))},peerRequestDiagnostics:{capacity:64,dropped:this.peerRequestDropped,counters:{...this.peerRequestCounters},records:this.peerRequestRecords.map(o=>({...o}))},uploadRefusalDiagnostics:{counters:{...this.uploadRefusalCounters}},admissionDiagnostics:{calls:{...this.admissionCallCounters}},signalling:{samples:this.signallingSamples.length,medianMs:Be(this.signallingSamples,.5),p90Ms:Be(this.signallingSamples,.9),clock:{...this.session?this.session.clockDiagnostics():{aheadRejected:null,staleRejected:null,maxAheadSeconds:null,signalSamples:null,signalAgeMedianSeconds:null},origin:ss(this.originClockSamples)}},segments:{originLoaded:e.originLoaded,raced:e.raced,noPeers:e.noPeers,sampledOut:e.sampledOut,skipped:e.skipped,aborted:e.aborted,peerInTime:e.peerInTime,peerLate:e.peerLate,peerMiss:e.peerMiss,peerCorrupt:e.peerCorrupt,peerUnverified:e.peerUnverified,inTimeShare:i(e.peerInTime,r),sampledInTimeShare:i(e.peerInTime,s),observedInTimeShare:t?i(e.peerInTime,e.originLoaded):null,sampledInTimeByteShare:i(e.peerInTimeBytes,e.sampledOriginBytes),observedInTimeByteShare:t?i(e.peerInTimeBytes,e.bytesFromOrigin):null,peerFirstShare:t?null:i(e.peerFirstLoaded,e.peerFirstLoaded+e.originLoaded),peerFirstByteShare:t?null:i(e.peerFirstBytes,e.peerFirstBytes+e.bytesFromOrigin),peerFirstLoaded:e.peerFirstLoaded,zeroBudgetPeerRaces:e.zeroBudgetPeerRaces,zeroBudgetPeerRaceWins:e.zeroBudgetPeerRaceWins,abrPeerSamplesWithheld:e.abrPeerSamplesWithheld,originFallbacks:e.originFallbacks,coordinatedWaits:e.coordinatedWaits,coordinatedPeerLoads:e.coordinatedPeerLoads,peerSkippedLate:e.peerSkippedLate,peerProjectedLate:e.peerProjectedLate,peerWaitExtended:e.peerWaitExtended,peerAbandoned:e.peerAbandoned,peerNoFit:e.peerNoFit,peerUntestedTrial:e.peerUntestedTrial,peerUntestedTrialLoaded:e.peerUntestedTrialLoaded,commitmentRequests:e.commitmentRequests,commitmentRejected:e.commitmentRejected,commitmentUnavailable:e.commitmentUnavailable,firstPeerSegmentAtMs:this.firstPeerSegmentAtMs,peerLatencyMedianMs:Be(this.peerLatencySamples,.5),peerLatencyP90Ms:Be(this.peerLatencySamples,.9),originLatencyMedianMs:Be(this.originLatencySamples,.5)},bytes:{fromOrigin:e.bytesFromOrigin,fromPeers:e.bytesFromPeers,peerFirst:e.peerFirstBytes,uploaded:e.bytesUploaded,uploadsServed:e.uploadsServed,uploadsRefused:e.uploadsRefused,uploadsCancelled:e.uploadsCancelled,uploadCancelledBytes:e.uploadCancelledBytes,uploadRemaining:this.#H(),uploadExhausted:this.#H()===0,held:this.heldBytes},relays:{connected:this.pool?.sockets.length??0,presenceSent:e.presenceSent,signalsSent:e.signalsSent,published:this.pool?.published??0,rejected:this.pool?.rejected??0,rejectedTimestamp:this.pool?.rejectedTimestamp??0,sinceDropped:this.pool?.sinceDropped??0,publishErrors:e.publishErrors},errors:{total:e.errors,byStage:{...this.errorsByStage}},core:{state:this.coreState,verifier:this.coreVerifier?"wasm":"js",selection:this.peerSelection.kind??"js",discovery:this.discovery.kind??"js",links:{...this.coreLinks},fallbacks:this.coreFallbacks,decided:{...this.coreDecided},transferWorker:{...this.transferWorker?.snapshot()??{},state:this.transferWorkerState,reason:this.transferWorkerReason},multiHolder:{enabled:this.#A(),...this.multiHolder,originRangeOutcomes:{...this.originRangeOutcomes},peerFlow:{...this.peerFlow,modelEvaluations:{...this.peerFlow.modelEvaluations},lastVerifiedShortBatch:this.peerFlow.lastVerifiedShortBatch&&{...this.peerFlow.lastVerifiedShortBatch},lastModel:this.peerFlow.lastModel&&{...this.peerFlow.lastModel},lastNoModel:this.peerFlow.lastNoModel&&{...this.peerFlow.lastNoModel,model:{...this.peerFlow.lastNoModel.model}}},timings:{durationMs:Qn(this.multiHolderTimings.map(o=>o[0])),slowestRequestMs:Qn(this.multiHolderTimings.map(o=>o[1])),requests:Qn(this.multiHolderTimings.map(o=>o[2]))}}},config:{originFallbackMs:this.options.originFallbackMs,maxPeerWaitMs:this.options.maxPeerWaitMs,originReserveMs:this.options.originReserveMs,sustainablePeerWait:this.options.sustainablePeerWait,zeroBudgetPeerRace:this.options.zeroBudgetPeerRace,lateHaveRace:this.options.lateHaveRace,lateWindowMs:this.options.lateWindowMs,maxPeers:this.options.maxPeers,maxUploadPeers:this.options.maxUploadPeers,maxUploadBytesPerSecond:this.options.maxUploadBytesPerSecond,maxUploadBytesPerSession:Number.isSafeInteger(this.options.maxUploadBytesPerSession)&&this.options.maxUploadBytesPerSession>=0?this.options.maxUploadBytesPerSession:null,serve:this.options.serve===!0,admit:typeof this.options.admit=="function",shadowSampleRate:this.options.shadowSampleRate,minLinkLifeMs:this.options.minLinkLifeMs,idleEvictMs:this.options.idleEvictMs,evictionCooldownMs:this.options.evictionCooldownMs,relays:Array.isArray(this.options.relays)?[...this.options.relays]:[]}}}#o(e,t){this.stopped||(this.counters.errors+=1,this.errorsByStage[e]=(this.errorsByStage[e]||0)+1)}#n(e,t){try{let r=t();r&&typeof r.catch=="function"&&r.catch(s=>this.#o(e,s))}catch(r){this.#o(e,r)}}#h(e,t){if(this.stopped)return null;let r=setTimeout(()=>{this.timers.delete(r),this.stopped||this.#n("timer",t)},Math.max(0,e));return this.timers.add(r),r}#M(e,t,r){let s=()=>{let i=e*t*(Math.random()*2-1);this.#h(e+i,()=>{try{r()}finally{s()}})};s()}#B(e,t){try{let r=ns(e,t);if(r===null)return;this.originClockSamples.push(r),this.originClockSamples.length>16&&this.originClockSamples.shift()}catch{}}#b(e){let t=this;return class{static relayswarmShadow=!0;constructor(s){this.inner=new e(s),this.hlsConfig=s,this.active=null,this.peerStats=null,this.peerContext=null,this.pendingCallbacks=null}get stats(){return this.peerStats||this.inner.stats}get context(){return this.peerContext||this.inner.context}load(s,i,o){this.abort(),this.releaseFetch=null,this.peerStats=null,this.originTrace=null,this.peerContext=s,s?.frag&&t.peerFragments.delete(s.frag);let a={source:"unobserved",positionSource:null,currentTime:null,bufferedEnd:null,playableEnd:null,fragmentStart:null,originReserveMs:null,uncappedMs:null},l=t.#Fe(s,a);if(t.#Y(s),t.options.peerSupplyHint&&t.#n("player-hint",()=>t.#R(s,l)),t.stopped||!s.frag||s.frag.sn==="initSegment"||s.part&&!t.options.swarmParts||!t.options.serveOnCellular&&Ht())return this.inner.load(s,i,o);if(l===0&&t.options.zeroBudgetPeerRace&&!this.hlsConfig.progressive&&t.#A()&&t.#l()){let A=new Map([...t.links.values()].filter(k=>t.#K(k,s)&&k.supportsRanges&&(t.remoteFraming.get(k.pubkey)??1)>=2&&!t.banned.has(k.pubkey)&&(k.have.size||t.options.lateHaveRace)).map(k=>[k,new Set(k.have)]));if(A.size)return this.loadCachedRace(s,i,o,a,A)}let c=i?.loadPolicy?.maxLoadTimeMs??i?.timeout;if(l===0&&t.options.latePeerRace&&!this.hlsConfig.progressive&&ve(s)&&Number.isFinite(c)&&c>0&&t.#l())return this.loadLatePeerRace(s,i,o,a,c);let u=new AbortController,d={};this.active=d;let f=I();Object.assign(this.inner.stats,{aborted:!1,loaded:0,total:0,chunkCount:0,bwEstimate:0,loading:{start:f,first:0,end:0},parsing:{start:0,end:0},buffering:{start:0,first:0,end:0}}),this.pendingCallbacks={callbacks:o,context:s};let g,p=null,m=()=>{clearTimeout(g),t.lifecycle.signal.removeEventListener("abort",b)};this.cancel=()=>{let A=this.active===d;return this.active=null,m(),u.abort(),A};let b=()=>{if(this.active!==d)return;this.active=null,this.pendingCallbacks=null,m(),u.abort(),t.counters.originFallbacks+=1,this.inner.stats.loading.start=0;let A=I(),k=!1,W=null,_=t.#C(s);_.then(h=>{!k&&!t.stopped&&(W=h,this.releaseFetch=t.#Z(h))}).catch(()=>{});let F=()=>k?!1:(k=!0,this.releaseFetch?.(),this.releaseFetch=null,!0),P=this.cancel;this.cancel=()=>(F(),P());let N=this.originTrace=t.#c(p,"fallback",()=>this.inner.stats);this.inner.load(s,i,{...o,onError:(...h)=>{N?.terminal("error",null,void 0,N!==this.originTrace),F(),o.onError?.(...h)},onTimeout:(...h)=>{N?.terminal("timeout",null,h[0],N!==this.originTrace),F(),o.onTimeout?.(...h)},onAbort:(...h)=>{N?.terminal("abort",null,h[0],N!==this.originTrace),F(),o.onAbort?.(...h)},onSuccess:(h,x,S,M)=>{if(k)return;let H=Vr(x),{copy:D,size:B}=t.#S(h,s);if(!k&&(W&&D&&t.#L(W,new Uint8Array(D)),!!F())){if(this.pendingCallbacks=null,N?.terminal("payload",B||null,x,N!==this.originTrace),We(t.originLatencySamples,I()-A),t.#X(t.renditionOriginSamples,s,I()-A),t.options.peerSupplyHint&&B){let U=t.#v(s);!t.hintSizes.has(U)&&t.hintSizes.size>=16&&t.hintSizes.delete(t.hintSizes.keys().next().value),t.hintSizes.set(U,B);let C=I()-A;C>0&&We(t.hintOriginRates,B/C)}o.onSuccess(h,x,S,M),t.#B(M,H),B&&!t.stopped&&t.#n("peer-first-origin",async()=>{if(t.counters.originLoaded+=1,t.counters.bytesFromOrigin+=B,!W){let U=await _;D&&!t.stopped&&t.#L(U,new Uint8Array(D))}})}}})};if(l===0)return p=t.#i(s,0,0,a),t.#E(s,l,"no-budget",null,a),b();let v=()=>{K.onDeadline?.()||(K.expired=!0,b())};g=setTimeout(v,l),t.lifecycle.signal.addEventListener("abort",b,{once:!0});let w=Math.max(t.options.originFallbackMs,t.options.maxPeerWaitMs),T=Math.max(l,Math.min(w,a.uncappedMs??l,a.sustainableMs??1/0));p=t.#i(s,l,T,a);let O={Loader:e,config:this.hlsConfig,loaderConfig:i},K={deadline:f+l,limit:f+T,originReserveMs:a.originReserveMs??t.options.originReserveMs,expired:!1,onDeadline:null,origin:O,extend:A=>{let k=Math.min(K.limit,A);return this.active!==d||k<=K.deadline?!1:(K.deadline=k,clearTimeout(g),g=setTimeout(v,Math.max(0,k-I())),!0)}};t.#ae(s,u.signal,K,l,a).then(A=>{if(!(this.active!==d||u.signal.aborted||t.stopped)){if(A&&!A.multi&&I()>=K.deadline&&t.#N(A.demand),!A||I()>=K.deadline&&!A.multi)return b();this.active=null,this.pendingCallbacks=null,m(),t.#O(this,A,s,o,f)}}).catch(A=>{this.active===d&&(t.#o("peer-first",A),b())})}loadCachedRace(s,i,o,a,l){let c=t.#i(s,0,t.options.maxPeerWaitMs,a),u={},d=new AbortController,f=I(),g=!0,p=!1,m=null,b,v;this.active=u,this.pendingCallbacks={callbacks:o,context:s},Object.assign(this.inner.stats,{aborted:!1,loaded:0,total:0,chunkCount:0,loading:{start:0,first:0,end:0}});let w=()=>{clearTimeout(v),t.lifecycle.signal.removeEventListener("abort",w),t.cachedRaces.delete(d),d.abort()};t.cachedRaces.add(d),t.lifecycle.signal.addEventListener("abort",w,{once:!0}),this.cancel=()=>{let A=g&&this.active===u;g=!1,this.active=null,w();try{this.inner.abort()}catch{}return A};let T=()=>!g||this.active!==u?!1:(g=!1,this.active=null,this.pendingCallbacks=null,w(),this.releaseFetch?.(),this.releaseFetch=null,!0);v=setTimeout(w,t.options.maxPeerWaitMs),t.counters.originFallbacks+=1,t.#E(s,0,"no-budget",null,a);let O=this.originTrace=t.#c(c,"cached",()=>this.inner.stats);try{this.inner.load(s,i,{...o,onProgress:(...A)=>{if(!g||this.active!==u){O?.progress(void 0,null,!0);return}let k=A[2]?.byteLength>0;k&&(p=!0,w()),O?.progress(A[0],k,!1),o.onProgress?.(...A)},onError:(...A)=>{O?.terminal("error",null,void 0,!g||this.active!==u),T()&&o.onError?.(...A)},onTimeout:(...A)=>{O?.terminal("timeout",null,A[0],!g||this.active!==u),T()&&o.onTimeout?.(...A)},onAbort:(...A)=>{O?.terminal("abort",null,A[0],!g||this.active!==u),T()&&o.onAbort?.(...A)},onSuccess:(A,k,W,_)=>{if((!g||this.active!==u)&&O?.terminal("payload",null,void 0,!0),!g||this.active!==u)return;let F=Vr(k),{copy:P,size:N}=t.#S(A,s);!g||this.active!==u||(m&&P&&t.#L(m,new Uint8Array(P)),T()&&(O?.terminal("payload",N||null,k),We(t.originLatencySamples,I()-f),t.#X(t.renditionOriginSamples,s,I()-f),o.onSuccess(A,k,W,_),t.#B(_,F),N&&!t.stopped&&t.#n("cached-race-origin",async()=>{if(t.counters.originLoaded+=1,t.counters.bytesFromOrigin+=N,!m){let h=await(b??t.#C(s));P&&!t.stopped&&t.#L(h,new Uint8Array(P))}})))}})}catch(A){throw T(),A}if(!g)return;b=t.#C(s),b.then(A=>{g&&!t.stopped&&(m=A,this.releaseFetch=t.#Z(A))}).catch(()=>{});let K={deadline:f+t.options.maxPeerWaitMs,limit:f+t.options.maxPeerWaitMs,originReserveMs:0,expired:!1,onDeadline:null,cachedOnly:l,lateHaveRace:t.options.lateHaveRace,peerOnly:!0,extend:()=>!1};t.#ae(s,d.signal,K,0,a).then(A=>{if(!(!A||!g||p||this.active!==u||d.signal.aborted||t.stopped||I()>=K.limit)){g=!1,this.active=null,this.pendingCallbacks=null,w(),this.releaseFetch?.(),this.releaseFetch=null,O?.abortRequest("peer-won");try{this.inner.abort()}catch{}t.counters.zeroBudgetPeerRaceWins+=1,t.#O(this,A,s,o,f)}}).catch(A=>{g&&!d.signal.aborted&&!t.stopped&&t.#o("cached-race",A)}).finally(w)}loadLatePeerRace(s,i,o,a,l){let c=t.#i(s,0,l,a),u={},d=new AbortController,f=I(),g=!0,p=!1,m=null,b;this.active=u,this.pendingCallbacks={callbacks:o,context:s},Object.assign(this.inner.stats,{aborted:!1,loaded:0,total:0,chunkCount:0,loading:{start:0,first:0,end:0}});let v=()=>g&&!p&&this.active===u&&!t.stopped,w=O=>!g||this.active!==u?!1:(g=!1,this.active=null,this.pendingCallbacks=null,b?.close(O),this.releaseFetch?.(),this.releaseFetch=null,!0);this.cancel=()=>{let O=g&&this.active===u;g=!1,this.active=null,b?.close("caller-abort"),this.releaseFetch?.(),this.releaseFetch=null;try{this.inner.abort()}catch{}return O};let T;b=t.#w({context:s,controller:d,entryAt:f,parentDeadline:f+l,current:v,arm:(O,K)=>(t.options.traceRequests&&t.traceLoads.set(O,c),t.#ae(O,d.signal,K,0,a).then(A=>{if(!A||!v()||d.signal.aborted||I()>=K.limit||!b.valid()||typeof K.revalidateAuthority!="function"||!K.revalidateAuthority())return!1;g=!1,this.active=null,this.pendingCallbacks=null,b.close("peer-won","won"),this.releaseFetch?.(),this.releaseFetch=null,T?.abortRequest("peer-won");try{this.inner.abort()}catch{}return t.counters.zeroBudgetPeerRaceWins++,t.#O(this,A,s,o,f),!0}))}),t.counters.originFallbacks++,t.#E(s,0,"no-budget",null,a),T=this.originTrace=t.#c(c,"late",()=>this.inner.stats);try{this.inner.load(s,i,{...o,onProgress:(...O)=>{if(!g||this.active!==u){T?.progress(void 0,null,!0);return}let K=O[2]?.byteLength>0;K&&(p=!0,b?.close("origin-progress")),T?.progress(O[0],K,!1),o.onProgress?.(...O)},onError:(...O)=>{T?.terminal("error",null,void 0,!g||this.active!==u),w("origin-error")&&o.onError?.(...O)},onTimeout:(...O)=>{T?.terminal("timeout",null,O[0],!g||this.active!==u),w("origin-timeout")&&o.onTimeout?.(...O)},onAbort:(...O)=>{T?.terminal("abort",null,O[0],!g||this.active!==u),w("origin-abort")&&o.onAbort?.(...O)},onSuccess:(O,K,A,k)=>{if((!g||this.active!==u)&&T?.terminal("payload",null,void 0,!0),!g||this.active!==u)return;let W=Vr(K),{copy:_,size:F}=t.#S(O,s);!g||this.active!==u||(m&&_&&t.#L(m,new Uint8Array(_)),w("origin-success")&&(T?.terminal("payload",F||null,K),We(t.originLatencySamples,I()-f),t.#X(t.renditionOriginSamples,s,I()-f),o.onSuccess(O,K,A,k),t.#B(k,W),F&&!t.stopped&&t.#n("late-race-origin",async()=>{if(t.counters.originLoaded++,t.counters.bytesFromOrigin+=F,!m){let P=await(b?.keyPromise??t.#C(s));_&&!t.stopped&&t.#L(P,new Uint8Array(_))}})))}})}catch(O){throw w("origin-throw"),O}g&&b?.keyPromise.then(O=>{g&&this.active===u&&!t.stopped&&(m=O,this.releaseFetch=t.#Z(O))}).catch(()=>{})}abort(){if(this.originTrace?.abortRequest("caller-abort"),this.releaseFetch?.(),this.releaseFetch=null,this.cancel?.()&&this.pendingCallbacks){let{callbacks:i,context:o}=this.pendingCallbacks;this.pendingCallbacks=null,this.inner.stats.aborted=!0,t.counters.aborted+=1,i.onAbort?.(this.inner.stats,o,null)}else this.inner.abort()}destroy(){let s;try{let i=this.peerStats;i?.aborted===!1&&(s=i)}catch{}try{this.originTrace?.abortRequest("destroy"),this.releaseFetch?.(),this.releaseFetch=null,this.cancel?.(),this.pendingCallbacks=null,this.inner.destroy()}finally{try{s&&s.aborted!==!1&&(s.aborted=!1)}catch{}}}getCacheAge(){return this.peerStats?null:this.inner.getCacheAge?.()??null}getResponseHeader(s){return this.peerStats?null:this.inner.getResponseHeader?.(s)??null}}}#S(e,t){try{let r=e.data,s=r?.byteLength;return s?{copy:this.#xe()&&!t?.[ke]?r.slice(0):null,size:s}:{copy:null,size:0}}catch{return{copy:null,size:0}}}#l(){return this.cachedRaces.size+[...this.latePeerOwners.values()].filter(e=>!e.attempted).lengtha===null?null:Math.max(0,Math.round(a-this.transportStartedAt));this.latePeerRows.push({id:e.id,atMs:o(I()),sequence:i.sn,cc:i.cc,level:i.level,genuineAtMs:o(e.genuineAt),windowEndAtMs:o(e.windowEnd),armedAtMs:o(e.armedAt??null),deadlineAtMs:o(e.peerLimit??null),outcome:t,reason:r,...e.dependencyAt!==null?{startupDependencyAtMs:o(e.dependencyAt),startupDeadlineAtMs:o(e.dependencyDeadline)}:{},...s?{holders:s.map(a=>this.#U(a.pubkey))}:{}})}#a(e){for(let t of[...this.latePeerOwners.values()])t.close(e)}#k(){for(let e of[...this.latePeerOwners.values()])e.refresh()}#w(e){let t=ve(e.context);if(!t||!this.#l())return null;let r=e.context[ke],s=e.entryAt,i=this.hls?.media,o={...e,identity:t,id:this.latePeerNextId++,generation:this.latePeerGeneration,streamId:this.options.streamEvent?.id,genuineAt:null,dependencyAt:null,dependencyDeadline:null,windowEnd:null,attempted:!1,closed:!1,key:null,timer:null},a=new AbortController,l=()=>{clearTimeout(o.timer),this.timers.delete(o.timer),o.timer=null};o.close=(f,g="retired")=>{o.closed||(o.closed=!0,l(),a.abort(),r?.onGenuine===o.refresh&&delete r.onGenuine,this.latePeerOwners.delete(o.id),this.cachedRaces.delete(o.controller),o.controller.abort(),this.#f(o,g,f))};let c=()=>{let f=r?r.genuine?.():{at:s,context:e.context};if(f)return{...f,role:"genuine"};let g=r?.startupDependency?.();return g&&Number.isFinite(g.at)&&Number.isFinite(g.deadline)&&g.signal?.aborted===!1?{...g,role:"startup-buffer-dependency"}:null},u=(f,g)=>this.links.get(f.pubkey)===f&&this.#K(f,g)&&f.supportsRanges===!0&&(this.remoteFraming.get(f.pubkey)??1)>=2&&!this.banned.has(f.pubkey)&&f.have.has(o.key),d=()=>{let f=c();return!f||!Number.isFinite(f.at)||ve(f.context)?.key!==t.key?null:r?{...f.context,[ke]:r}:f.context};o.valid=()=>!o.closed&&e.current()&&!this.stopped&&o.generation===this.latePeerGeneration&&o.streamId===this.options.streamEvent?.id&&d()!==null&&!i?.paused&&!i?.ended&&I()<(o.peerLimit??o.windowEnd??e.parentDeadline)&&[...o.validatedPeers??[]].every(([f,g])=>this.links.get(f.pubkey)===f&&!f.closed&&!this.banned.has(f.pubkey)&&(!this.options.admit||this.admitted.get(f.pubkey)?.ticket===g)),o.refresh=()=>{if(o.closed)return;if(!e.current()||this.stopped||o.generation!==this.latePeerGeneration||o.streamId!==this.options.streamEvent?.id)return o.close("inactive");let f=c();if(!f){o.windowEnd!==null&&o.close(o.dependencyAt!==null?"startup-buffer-ended":"no-genuine-consumer");return}let g=d();if(!g||i?.paused||i?.ended)return o.close("context-or-playback");if(o.windowEnd===null){let b=f.role==="startup-buffer-dependency";o.genuineAt=b?null:f.at,o.dependencyAt=b?s:null,o.dependencyDeadline=b?f.deadline:null,o.windowEnd=Math.min(e.parentDeadline,b?f.deadline:1/0,(b?s:f.at)+Math.min(4e3,this.options.lateWindowMs)),b&&f.signal.addEventListener("abort",()=>o.close("startup-buffer-ended"),{once:!0,signal:a.signal}),this.#f(o,"entered",b?"startup-buffer-dependency":"genuine-demand"),o.timer=this.#h(Math.max(0,o.windowEnd-I()),()=>o.close("window-expired","expired"))}else f.role==="genuine"&&o.genuineAt===null&&(o.genuineAt=f.at);if(I()>=o.windowEnd)return o.close("window-expired","expired");if(o.attempted||!o.key||!this.#A())return;let p=[...this.links.values()].filter(b=>u(b,g));if(!p.length)return;o.attempted=!0;let m=Math.min(o.windowEnd,I()+Math.min(2500,this.options.maxPeerWaitMs),e.parentDeadline);o.armedAt=I(),o.peerLimit=m,l(),o.timer=this.#h(Math.max(0,m-I()),()=>o.close("peer-expired","expired")),this.cachedRaces.add(o.controller),this.#f(o,"armed","accepted-exact-have",p),(async()=>{let b=await Promise.all(p.map(async A=>{if(!this.options.admit)return A;let k=this.admissionChecks.get(A.pubkey)?.ticket??this.admitted.get(A.pubkey)?.ticket,W=!1;try{W=await lt(()=>this.#x(A.pubkey,k,"other"),o.controller.signal,Math.max(0,Math.min(this.options.admissionTimeoutMs,m-I())))===!0}catch{}return!W&&!o.closed&&A.close("admission"),W?A:null}));if(o.closed)return;let v=d();if(!e.current()||!v||I()>=m||o.generation!==this.latePeerGeneration)return o.close("inactive-after-admission");let w=b.filter(A=>A&&u(A,v));if(!w.length)return o.close("admission-or-have-refused","refused");o.validatedPeers=new Map(w.map(A=>[A,this.admitted.get(A.pubkey)?.ticket]));let T=ve(v)?.context;if(!T||!o.valid())return o.close("context-after-admission");let O={deadline:m,limit:m,originReserveMs:0,expired:!1,onDeadline:null,knownKey:o.key,cachedOnly:new Map(w.map(A=>[A,new Set([o.key])])),lateHaveRace:!1,peerOnly:!0,extend:()=>!1,currentValid:o.valid,revalidateAuthority:!0};!await e.arm(T,O)&&!o.closed&&o.close("peer-no-result","refused")})().catch(()=>{o.closed||o.close("peer-error","refused")})},this.latePeerOwners.set(o.id,o),r&&(r.onGenuine=o.refresh);for(let f of["pause","ended","emptied"])i?.addEventListener?.(f,()=>o.close(`media-${f}`),{signal:a.signal});return o.keyPromise=this.#C(e.context).then(f=>(o.key=f,o.closed||o.refresh(),f),f=>{throw o.close("key-refused","refused"),f}),o.keyPromise.catch(()=>{}),o.refresh(),o}#O(e,t,r,s,i){let o=I(),a=t.bytes.byteLength;e.peerStats=e.inner.stats,Object.assign(e.peerStats,{aborted:!1,loaded:a,total:a,chunkCount:1,bwEstimate:a*8e3/Math.max(1,o-i),loading:{start:i,first:o,end:o},parsing:{start:0,end:0},buffering:{start:0,first:0,end:0}});let l=t.multi?t.peerBytes:a;if(this.counters.bytesFromPeers+=l,l>0)if(t.multi){let f=new Map(t.contributions.filter(p=>p.bytes>0).map(p=>[p.connection,p.bytes])),g=new Map((t.shortRefreshes||[]).map(p=>[p.connection,p.at]));for(let p of this.links.values())f.has(p.pc)&&this.#pe(p,f.get(p.pc),g.get(p.pc))}else{let f=this.links.get(t.pubkey);f?.pc===t.connection&&this.#pe(f,a)}let c=f=>{if(l>0&&(this.counters.peerFirstLoaded+=1),this.counters.peerFirstBytes+=l,l>0){if(!t.multi)this.discovery.holderDelivered(t.holderContext,t.pubkey);else{let g=new Map(t.contributions.filter(p=>p.bytes>0).map(p=>[p.connection,p.bytes]));for(let p of this.links.values())g.has(p.pc)&&this.discovery.holderDelivered(t.holderContext,p.pubkey)}this.discovery.verified(t.discoveryContext)&&this.discovery.window?.context===t.discoveryContext&&this.#q(),this.firstPeerSegmentAtMs===null&&(this.firstPeerSegmentAtMs=Date.now()-this.startedAt),We(this.peerLatencySamples,o-i),f.frag&&this.peerFragments.add(f.frag)}},u=()=>{if(typeof this.options.onPeerDelivery=="function"){let f=t.multi?t.contributions:[{connection:t.connection,bytes:a}];for(let{connection:g,bytes:p}of f)if(!(p<=0))try{let m=this.options.onPeerDelivery({connection:g,bytes:p});m&&typeof m.then=="function"&&Promise.resolve(m).catch(()=>{})}catch{}}},d=f=>{c(f),u()};r[ke]?Object.assign(r[ke],{peerBytes:l,accept:d,commit:c,notify:u}):d(r),!r[ke]&&this.#p()&&!this.held.has(t.key)&&this.#L(t.key,t.bytes.slice()),s.onSuccess({url:r.url,data:t.bytes.buffer,code:200},e.peerStats,r,null)}async#R(e,t){if(!e?.frag||e.frag.sn==="initSegment"||e.part||this.stopped)return;let r=++this.hintGeneration,s=this.hls?.levels||[],i=s.length?s.map((a,l)=>{if(l===e.frag.level)return e;let c=a.details?.fragments?.find(u=>u.sn===e.frag.sn&&u.cc===e.frag.cc);return c?{url:c.url,frag:c,rangeStart:c.byteRangeStartOffset,rangeEnd:c.byteRangeEndOffset}:null}):[e],o=await Promise.all(i.map(async(a,l)=>{let c=a?this.#v(a):`main:${l}`,u=a?await this.#C(a):null;if(this.stopped||r!==this.hintGeneration)return null;let d=a&&this.discovery.contexts.get(a.frag.type||"main"),f=u?[...this.links.values()].filter(T=>this.#P(T)&&T.have.has(u)&&T.supportsRanges===!0&&(this.remoteFraming.get(T.pubkey)??1)>=2&&!this.banned.has(T.pubkey)&&!(d?.rendition===c&&this.discovery.stale(d,T.pubkey))).map((T,O)=>{let K=this.peerSelection.summary(T).throughputBytesPerSecond;return[O+1,null,K?K/1e3:null]}):[],g=a?this.renditionSizes.get(c)??this.hintSizes.get(c)??null:null,p=a?Math.ceil((s[l]?.bitrate??0)*(a.frag.duration??0)/8):0,m=g??(p>0&&p<=this.options.maxSegmentBytes?p:null),b=Be(this.renditionOriginSamples.get(c)||[],.5),v={rendition:c,size:m,peers:f,origin:[null,m&&b?m/b:Be(this.hintOriginRates,.5)],sharedFirstByteMs:this.peerSelection.firstByteMs(),sharedRate:this.peerSelection.rate(),availableMs:t,maxHolders:this.options.maxHoldersPerObject},w=this.core?.playerHint(v);return w&&this.options.traceRequests&&this.#e({k:"playerHint",at:this.#s(),input:v,out:w}),w?{...w,level:a?.frag.level??l,sequence:a?.frag.sn??null,sizeEstimate:m,sizeEstimateSource:g!==null?"observed":m!==null?"playlist-bitrate":null,knowledge:"linked-have"}:null}));this.stopped||r!==this.hintGeneration||(this.playerHints=o.filter(Boolean),this.playerHints.length&&this.options.onPlayerHint?.(structuredClone(this.playerHints)))}#v(e){let t=Ot(e);return t?`${t.mediaType}:${t.playlist}`:`${e.frag.type||"main"}:${e.frag.level}`}#Y(e){if(this.stopped||!e.frag||e.frag.sn==="initSegment"||this.coreWait)return;let t=this.#v(e);if(this.latePeerOwners.size&&e.frag.type==="main"){let s=ve(e)?.scope;if(s)for(let i of[...this.latePeerOwners.values()])i.identity.scope!==s&&i.close("rendition")}this.discovery.context(e.frag.type||"main",t),this.#j(!1);let r=this.renditions.get(t);for(let[s,i]of this.renditions)i=8&&this.renditions.delete(this.renditions.keys().next().value),this.renditions.set(t,Date.now()),this.rendition=t,!r)for(let s of this.links.values())s.sendContribution(this.#p(),t)}#I(e,t,r){let s=Date.now(),i=[...this.links.values()].filter(l=>!l.closed&&l.contribution?.serving&&(l.renditions.get(t)||0)>s-3e4);if(!i.length)return!1;if(i.some(l=>(l.fetching.get(e)||0)>s))return!0;let o=r?.frag;if(o?.type==="main"&&Number.isInteger(o.level)&&o.level>=0&&this.hls?.levels?.[o.level]?.details?.live===!1)return!1;if(!this.#p())return!0;let a=l=>[...l].map((c,u)=>(parseInt(c,16)^parseInt(e[u],16)).toString(16)).join("");return i.some(l=>a(l.pubkey)=this.options.maxConcurrentRaces)return()=>{};let t=this.originFetches.get(e)||0;this.originFetches.set(e,t+1);for(let s of this.links.values())s.sendFetching(e,2e3);let r=!1;return()=>{if(r)return;r=!0;let s=(this.originFetches.get(e)||1)-1;if(s>0)this.originFetches.set(e,s);else{this.originFetches.delete(e);for(let i of this.links.values())i.sendFetching(e,0)}}}#Fe(e,t){if(e?.[ke])return t.source="warm-ahead",0;let r=this.hls?.media,s=1/0;if(this.options.sustainablePeerWait){let i=null;try{let l=e?.part,c=l?l.duration:e?.frag?.duration;Number.isFinite(c)&&c>0&&Number.isFinite(c*1e3)&&(i=c*1e3)}catch{}let o=Be(this.#W(e),.9),a=o===null?null:o*1.25+100;s=i===null||a===null?0:Math.max(0,i-a),Object.assign(t,{durationMs:i,originRecoveryMs:a,sustainableMs:s})}if(!r)return t.source="no-media",Math.min(this.options.originFallbackMs,s);try{for(let i=0;ir.currentTime){let o=Math.max(this.options.originReserveMs,(Be(this.#W(e),.9)||0)*1.25+100),a,l,c,u=(a=e?.part?.start)??e?.frag?.start,d=Number.isFinite(u)&&u>r.currentTime?Math.min(l=r.buffered.end(i),u):l=r.buffered.end(i),f=Math.max(0,(d-(c=r.currentTime))*1e3-o),g=Math.min(this.options.originFallbackMs,f,s);try{let p=m=>Number.isFinite(m)?m:null;Object.assign(t,{source:"buffer",positionSource:a==null?"fragment":"part",currentTime:p(c),bufferedEnd:p(l),playableEnd:p(d),fragmentStart:p(u),originReserveMs:p(o),uncappedMs:p(f)})}catch{}return g}}catch{return t.source="error",0}return t.source="no-buffer",0}async#C(e){let t=(this.options.segmentKey||to)(e.url||e.frag.url,e);if(typeof t!="string"||!t)throw new Error("Invalid segment key.");let r=e.rangeEnd?`#${e.rangeStart||0}-${e.rangeEnd}`:"";return Pt(eo.encode(`${this.options.swarmId} +${t}${r}`))}#qe(e){if(this.holderLabels.has(e)||(this.holderLabels.set(e,this.holderLabelNext++),this.holderLabels.size<=64))return;let t=[...this.holderLabels.keys()].find(r=>!this.links.has(r))??this.holderLabels.keys().next().value;this.holderLabels.delete(t)}#U(e){return this.holderLabels.get(e)??0}#je({key:e,rendition:t,context:r}){let s=l=>l.sort((c,u)=>c-u).slice(0,8),i=[],o=[],a=[];for(let l of this.links.values()){let c=this.#U(l.pubkey);this.#F(l,t)&&(i.push(c),this.discovery.stale(r,l.pubkey)&&a.push(c)),l.have.has(e)&&o.push(c)}return{holders:s(i),haveHolders:s(o),staleHolders:s(a),heldMissHolders:[]}}#N(e,{everyServing:t=!1,unfit:r=[]}={}){let{key:s,rendition:i,context:o}=e;if(!(!o||e.recorded)){e.recorded=!0;try{let a=[...this.links.values()].filter(u=>this.#F(u,i));if(t&&![...this.links.values()].some(u=>u.have.has(s))){for(let u of a)this.discovery.holderMiss(o,u.pubkey,s);return}let l=a.filter(u=>e.asked.has(u.pubkey)||r.includes(u.pubkey)),c=[];for(let u of l)this.discovery.holderMiss(o,u.pubkey,s)&&(this.discovery.counters.heldMiss++,c.push(this.#U(u.pubkey)));c.length&&e.row?.heldMissHolders&&(e.row.heldMissHolders=c.sort((u,d)=>u-d).slice(0,8))}catch{}}}#We(e,t){this.stopped||this.options.mode!=="peer-first"||this.discovery.counters.checks!==t||!this.discovery.current(e)||!this.#he(e)||!this.#Re(e)||this.discovery.hinted(e,r=>this.#Te(r))&&this.discovery.counters.staleBlocked++}#E(e,t,r,s,i,o,a,l=!1,c){try{if(!ro.includes(r))return;let u=m=>Number.isSafeInteger(m)&&m>=0?m:null,d=null,f=null;try{d=u(e?.frag?.cc)}catch{}try{f=u(e?.frag?.level)}catch{}let g=I()-this.transportStartedAt,p={atMs:Number.isFinite(g)?Math.max(0,Math.round(g)):0,cc:d,level:f,budgetMs:Number.isFinite(t)&&t>=0?t:null,reason:r,matchingHave:typeof s=="boolean"?s:null,budgetGeometry:{...i}};if(o&&(p.projection={...o}),l===!0&&(p.trial=!0),a){try{Object.assign(p,this.#je(a))}catch{Object.assign(p,{holders:null,haveHolders:null,staleHolders:null,heldMissHolders:null})}a.row=p}this.peerEligibilityCounters[r]=Oe(this.peerEligibilityCounters[r]),this.peerEligibilityRecords.length===64&&(this.peerEligibilityRecords.shift(),this.peerEligibilityDropped=Oe(this.peerEligibilityDropped)),this.peerEligibilityRecords.push(p),this.options.traceRequests&&this.#e({k:"eligibility",load:c===void 0?this.#d(e):c,at:this.#s(),...structuredClone(p)})}catch{}}#X(e,t,r){let s=this.#v(t);!e.has(s)&&e.size>=16&&e.delete(e.keys().next().value);let i=e.get(s)||[];We(i,r),e.set(s,i)}#W(e){try{let t=e?.frag&&this.renditionOriginSamples.get(this.#v(e));return t?.length?t:this.originLatencySamples}catch{return this.originLatencySamples}}#Ke(e,t,r,s){if(!(t>0)||!Number.isFinite(t)||rXn&&o.firstBytes.shift();let l=s-r;l>=Wr&&i>=Kr&&(o.flows.push({value:Math.min(1e6,i/l),flowMs:l,at:a}),o.flows.length>Xn&&o.flows.shift())}#pe(e,t,r=null){if(!e||e.closed||!Number.isSafeInteger(t)||t<=0)return;let s=this.#J(e);Number.isFinite(r)&&(s.flows=s.flows.filter(i=>i.at>=r)),s.usefulAt=I()}#$e(e,t,r){let s=this.#J(e),i=I();s.firstBytes=s.firstBytes.filter(f=>i-f.at<=Jn),s.flows=s.flows.filter(f=>i-f.at<=Jn);let o=s.firstBytes.reduce((f,g)=>f===null?g.value:(f+g.value)/2,null),a=s.flows.filter(f=>f.flowMs>=(o??0)*3),l=ml((a.length>=2?a:s.flows).map(f=>f.value),.75),c=l!==null&&(o??0)+r/l<=t,u=l===null&&(o??0){let g=p=>Number.isFinite(p)&&p>=0?p:null;this.peerFlow.modelEvaluations[f]=Oe(this.peerFlow.modelEvaluations[f]),this.peerFlow.lastModel={decision:f,availableMs:g(t),pieceSize:g(r),firstByteMs:g(o),rateBytesPerSecond:l===null?null:g(l*1e3),probeAgeMs:g(i-s.probeAt),usefulAgeMs:g(i-s.usefulAt)}};if(!c&&!u){if(i-s.probeAt>=ul)return d("refresh"),{state:s,firstByteMs:null,rate:null,refresh:!0};if(l===null)return d("cooldown-blocked"),null;d("known-slow")}else d(c?"fit":"useful-unknown");return{state:s,firstByteMs:o,rate:l,refresh:!1}}#Ge(e,t){let r=Be(this.renditionOriginSamples.get(t)||[],.5);if(r===null)return null;let s=null;for(let i of this.links.values()){let o=i.fetching.get(e)||0;o>Date.now()&&(s=Math.min(s??1/0,o-2e3))}return Math.max(0,r-(s===null?0:Date.now()-s))}#ge(e,t,r){let s=r.limit-I(),i=this.peerSelection.firstByteMs();if(t!==null&&t+(i??0)>s)return"late";if(e===null||t===null)return"unknown";let o=t+e;return o<=s?"fits":Date.now()-this.peerSelection.lastObservedAt>=yl?"stretch":o>s*1.25?"late":"stretch"}#me(e,t,r){let s=e==="fits"?I()+t*1.25+100:e==="stretch"?r.limit:null;s!==null&&r.extend(s)&&(this.counters.peerWaitExtended+=1)}#Q(e,t,r,s){let i=a=>Number.isFinite(a)?Math.round(a):null,o=this.peerSelection.rate();return{stage:e,transferMs:i(t),holderWaitMs:i(r),roomMs:i(s.limit-I()),firstByteMs:i(this.peerSelection.firstByteMs()),rateBytesPerSecond:Number.isFinite(o)?Math.round(o*1e3):null}}#ye(e,t){for(let r of this.links.values())if(!(!this.#P(r)||this.banned.has(r.pubkey)||!r.have.has(e))&&this.peerSelection.summary(r).attempts===0&&!(t&&this.discovery.stale(t,r.pubkey)))return r;return null}#be(e,t){return t.limit-I()>(this.peerSelection.firstByteMs()??0)&&!!this.#ye(e.key,e.context)}async#ae(e,t,r,s,i){let o=this.options.traceRequests?this.#d(e):null,a=r.deadline;if(this.options.transferWorkerUrl!==void 0&&this.transferWorkerState!=="ready")return null;let l=this.discovery.contexts.get(e.frag.type||"main"),c=r.knownKey??await this.#C(e);if(t.aborted||this.stopped||r.currentValid&&!r.currentValid())return this.#E(e,s,"aborted-before-eligibility",null,i,void 0,void 0,!1,o),null;if(r.cachedOnly){let P=h=>[...r.cachedOnly].filter(([x,S])=>(!h||S.has(c))&&x.have.has(c)&&this.links.get(x.pubkey)===x&&this.#K(x,e)&&!this.banned.has(x.pubkey)&&x.supportsRanges===!0&&(this.remoteFraming.get(x.pubkey)??1)>=2).map(([x])=>x),N=P(!0);if(!N.length&&r.lateHaveRace){for(N=P(!1);!N.length&&!t.aborted&&!this.stopped&&I()0}if(t.aborted||this.stopped||I()>=r.limit||(r.cachedHolders=new Set(N),!r.cachedHolders.size||!this.#A()))return null;this.counters.zeroBudgetPeerRaces+=1}let u=this.#v(e),d=l?.rendition===u&&this.discovery.contexts.get(l.mediaType)===l?l:null;if(d&&!r.cachedOnly){this.discovery.demand(l.mediaType,u,c);let P=this.discovery.counters.checks;this.#re();try{this.#We(d,P)}catch{}}let f={key:c,rendition:u,context:d,recorded:!1,asked:new Set,row:null},g=![...this.links.values()].some(P=>P.have.has(c));if(g&&!this.#I(c,u,e))return this.#E(e,s,"no-have-no-wait",!1,i,void 0,f,!1,o),null;let p=this.renditionSizes.get(u),m=g?this.#Ge(c,u):0,b=p?this.peerSelection.projectMs(p):null,v=!g&&this.#A()&&[...this.links.values()].some(P=>this.#K(P,e)&&P.supportsRanges===!0&&P.have.has(c)&&!this.banned.has(P.pubkey)&&(this.remoteFraming.get(P.pubkey)??1)>=2&&!(d&&this.discovery.stale(d,P.pubkey))),w=r.cachedOnly||v?"unknown":this.#ge(b,m,r),T=null;if(w==="late"&&!g&&this.#be(f,r)&&(T=this.#Q("entry",b,m,r),w="stretch"),w==="late")return this.#E(e,s,"projected-late",!g,i,this.#Q("entry",b,m,r),f,!1,o),this.#N(f,{everyServing:!0}),this.counters.peerProjectedLate+=1,null;this.#me(w,m+b,r),g&&(this.#E(e,s,"no-have-wait",!1,i,void 0,f,!1,o),this.counters.coordinatedWaits+=1);let O=r.deadline-I();if(t.aborted||this.stopped||O<=0)return null;this.counters.commitmentRequests+=1;let K=lt(P=>{if(t.aborted||this.stopped||I()>=r.deadline)throw new Error("Commitment load no longer active.");return this.options.getCommitment(e,{signal:P})},t,O).then(P=>({ok:!0,event:P}),()=>({ok:!1}));if(g){for(;!t.aborted&&!this.stopped&&I()N.have.has(c));){if(!this.#I(c,u,e))return this.#E(e,s,"wait-no-longer-eligible",!1,i,void 0,f,!1,o),null;await this.#ee(c,Math.min(100,r.deadline-I()),t)}let P=t.aborted||this.stopped;if(P||I()>=r.deadline)return this.#E(e,s,P?"wait-aborted":"wait-expired",null,i,void 0,f,!1,o),(!P||r.expired&&!this.stopped)&&this.#N(f,{everyServing:!0}),null}this.#E(e,s,g||r.lateHaveMatched?"have-after-wait":"have-at-entry",!0,i,T??void 0,f,T!==null,o);let A,k;try{let P=await K;if(!P.ok)throw new Error("Commitment unavailable.");k=P.event,A=this.#ce(P.event,{streamEvent:this.options.streamEvent,swarmId:this.options.swarmId,key:c,context:e,maxSegmentBytes:this.options.maxSegmentBytes,delegation:this.options.delegation,revokedDelegationIds:this.options.revokedDelegationIds,delegationRevocations:this.options.delegationRevocations})}catch{return this.stopped||(this.counters.commitmentUnavailable+=1),null}if(!A)return this.counters.commitmentRejected+=1,null;if(r.currentValid&&!r.currentValid()||(r.revalidateAuthority===!0&&(r.revalidateAuthority=()=>!!this.#ce(k,{streamEvent:this.options.streamEvent,swarmId:this.options.swarmId,key:c,context:e,maxSegmentBytes:this.options.maxSegmentBytes,delegation:this.options.delegation,revokedDelegationIds:this.options.revokedDelegationIds,delegationRevocations:this.options.delegationRevocations})),t.aborted||this.stopped)||r.cachedOnly&&A.v!==3)return null;if(!this.renditionSizes.has(u)&&this.renditionSizes.size>=16&&this.renditionSizes.delete(this.renditionSizes.keys().next().value),this.renditionSizes.set(u,A.size),A.v===3&&this.options.multiHolder){let P=await this.#Xe(e,t,r,c,A,l,o);if(P!==void 0)return P&&g&&(this.counters.coordinatedPeerLoads+=1),P&&{...P,holderContext:d}}if(r.cachedOnly)return null;let W=this.peerSelection.projectMs(A.size),_=this.#ge(W,0,r);if(_==="late"&&!g&&(T!==null||this.#be(f,r))&&(T=this.#Q("commitment",W,0,r),_="stretch",f.row&&(f.row.projection={...T},f.row.trial=!0)),_==="late")return this.#E(e,s,"projected-late",!0,i,this.#Q("commitment",W,0,r),f,!1,o),this.counters.peerProjectedLate+=1,null;this.#me(_,W,r);let F=new Set;for(;!t.aborted&&!this.stopped&&I()P||(N??0)>P)return this.counters.peerSkippedLate+=1,null;let h=($,ne)=>this.peerSelection.estimate($,A.size)===null||this.peerSelection.estimate($,A.size)*1.25+25<=ne,x=T&&F.size===0?this.#ye(c,f.context):null;x&&this.peerSelection.markSelected(x);let S=x??this.peerSelection.select([...this.links.values()].filter($=>this.#P($)),c,F,A.size,P);if(!S){if(![...this.links.values()].some($=>!$.closed&&!F.has($.pubkey)&&$.have.has(c)&&h($,P)))return this.counters.peerNoFit+=1,this.#N(f,{unfit:[...this.links.values()].filter($=>!$.closed&&!F.has($.pubkey)&&$.have.has(c)&&!h($,P)).map($=>$.pubkey)}),null;await this.#ee(c,Math.min(100,r.deadline-I()),t);continue}F.add(S.pubkey),f.asked.add(S.pubkey),x&&(this.counters.peerUntestedTrial+=1);let M=this.peerSelection.estimate(S,A.size);M!==null&&r.extend(I()+M*1.25+25)&&(this.counters.peerWaitExtended+=1);let H=I(),D=r.deadline-I(),B=[...this.links.values()].filter($=>this.#P($)&&!F.has($.pubkey)&&$.have.has(c)&&h($,D)).length,U=D-Math.min(2,B)*25,C=M===null?Math.min(D,Math.max(25,U)):Math.min(D,Math.max(25,D/Math.min(3,B+1),M*1.25+25)),z=this.#Je(t,H,A.size,r,N),ee;try{ee=await S.request(c,Math.max(1,C),{signal:z.signal,expectedSize:A.size,onProgress:z.progress,onResult:$=>this.#we(e,S,D,$,null,o)})}finally{z.done()}if(this.peerSelection.observe(z.observation()),z.abandoned)return this.#T(S,I()-H),this.counters.peerAbandoned+=1,this.#N(f),null;if(!ee||t.aborted||this.stopped){!t.aborted&&!this.stopped&&this.#T(S,I()-H);continue}let te=await Pt(ee);if(this.stopped)return null;if(ee.byteLength!==A.size||te!==A.sha256){if(this.#T(S,I()-H),this.counters.peerCorrupt+=1,this.banned.add(S.pubkey),f.asked.delete(S.pubkey),S.close("integrity"),t.aborted)return r.expired&&this.#N(f),null;continue}return t.aborted?(r.expired&&this.#N(f),null):A.expiresAt<=Math.floor(Date.now()/1e3)?null:(this.#T(S,I()-H,ee.byteLength),g&&(this.counters.coordinatedPeerLoads+=1),x&&(this.counters.peerUntestedTrialLoaded+=1),{key:c,bytes:ee,discoveryContext:l,holderContext:d,pubkey:S.pubkey,demand:f,connection:S.pc})}return!this.stopped&&(!t.aborted||r.expired)&&this.#N(f),null}#Ye(e){let t=this.transferIds.get(e);return t===void 0&&(t=this.nextTransferId++,this.transferIds.set(e,t)),t}#P(e){return!e.closed&&!e.busy&&!this.peerLeases.has(e)}#K(e,t){return this.#P(e)||!!(t?.[ke]&&!e.closed&&this.peerLeases.has(e))}#Ze(e,t,r){return this.peerAdmission.waited++,new Promise(s=>{let i,o=c=>{this.peerLeaseWaiters.delete(l)&&(clearTimeout(i),this.timers.delete(i),r.removeEventListener("abort",a),this.peerAdmission[c]++,s(c==="granted"))},a=()=>o("cancelled"),l=()=>{if(this.stopped||r.aborted)return a();if(I()>=t)return o("expired");e.some(c=>this.links.get(c.pubkey)===c&&this.#P(c))&&o("granted")};this.peerLeaseWaiters.add(l),r.addEventListener("abort",a,{once:!0}),i=setTimeout(()=>o("expired"),Math.max(0,t-I())),this.timers.add(i),l()})}async#Xe(e,t,r,s,i,o,a){if(r.currentValid&&!r.currentValid())return null;let l=this.options.transferWorkerUrl!==void 0;if(l&&(!this.#A()||this.transferWorkerState!=="ready"))return null;if(!this.#A()||!Array.isArray(i.pieces))return;let c=gl(e.url);if(!r.peerOnly&&this.originsWithoutRanges.has(c))return l?null:void 0;let u=w=>this.links.get(w.pubkey)===w&&!w.closed&&w.supportsRanges===!0&&w.have.has(s)&&!this.banned.has(w.pubkey)&&(this.remoteFraming.get(w.pubkey)??1)>=2&&(!r.cachedHolders||r.cachedHolders.has(w)),d=[...this.links.values()].filter(w=>u(w)&&this.#K(w,e)),f=()=>d.filter(w=>u(w)&&this.#P(w)),g=f();if(!g.length&&e?.[ke]&&d.some(w=>this.peerLeases.has(w))&&(await this.#Ze(d,r.limit,t),g=f()),this.stopped||t.aborted||I()>=r.limit||typeof r.revalidateAuthority=="function"&&!r.revalidateAuthority())return null;if(!g.length)return l?null:void 0;let p=new Map(g.map(w=>[w,this.#$e(w,Math.max(0,r.limit-I()),i.pieceSize)]).filter(([,w])=>w!==null));if(!p.size)return this.peerFlow.noModelTransfers=Oe(this.peerFlow.noModelTransfers),this.peerFlow.lastNoModel={candidateCount:g.length,model:{...this.peerFlow.lastModel}},this.counters.peerNoFit+=1,null;let m=[...p.keys()],b={};for(let w of m)this.peerLeases.set(w,b);this.peerAdmission.claims+=m.length;let v=()=>{t.removeEventListener("abort",v);for(let w of m)this.peerLeases.get(w)===b&&this.peerLeases.delete(w);for(let w of[...this.peerLeaseWaiters])this.#h(0,w);this.latePeerOwners.size&&this.#h(0,()=>this.#k())};t.addEventListener("abort",v,{once:!0});try{let w=new Map(m.map(S=>[this.#Ye(S),S])),T=Math.floor(r.limit),O=r.peerOnly?r.limit:r.limit+r.originReserveMs,K={size:i.size,sha256:i.sha256,pieces:i.pieces,deadline:T,maxHolders:this.options.maxHoldersPerObject,originReserveMs:0,...r.peerOnly?{peerOnly:!0}:{}},A;try{A=l?await this.transferWorker.transfer(K,{signal:t}):this.core.transfer(K)}catch{return null}if(this.stopped||t.aborted||l&&I()>=T||r.currentValid&&!r.currentValid()||typeof r.revalidateAuthority=="function"&&!r.revalidateAuthority()||m.some(S=>!u(S)||S.busy||this.peerLeases.get(S)!==b))return A?.free(),null;if(!A)return l||r.peerOnly?null:void 0;this.multiHolder.transfers+=1;let k=a,W=this.traceBase,_=(S,M,H)=>{let D=Math.floor(I()),B=C=>(this.options.traceRequests&&this.#e({k:"xfer",load:k,op:S,at:D-W,...M,out:C&&{c:C.commands.map(({t:z,peer:ee,p:te})=>({t:z,...ee!==void 0?{peer:ee}:{},...te?{p:[...te]}:{}})),next:C.next===null?null:C.next-W,late:C.late,finished:C.finished}}),C),U=H(D);return U?.then?U.then(B):B(U)};r.extend(r.limit);let F=i.pieceSize,P=({start:S,end:M})=>[S*F,Math.min(M*F,i.size)],N=[...w].map(([S,M])=>[S,p.get(M).firstByteMs,p.get(M).rate]),h=r.peerOnly?null:Be(this.#W(e),.5),x=r.peerOnly?null:[0,h?i.size/h:null];return await new Promise(S=>{let M=new Map,H=new Set,D=new WeakSet,B=new Map,U=new Map,C=!1,z=null,ee=null,te=null,$=0,ne=0,ue=this.latePeerGeneration,Z=this.options.streamEvent?.id,oe=this.hls,ge=this.hls?.media,Ie=this.transferWorker,Ke=new Map(m.map(y=>[y,{connection:y.pc,channel:y.channel,flow:new Cr}])),Ee=y=>{Ke.get(y)?.flow.discard(I())},Dt=(y,E,R,q,L)=>{let j=Ke.get(y),Y=I(),Q=q?.firstByteMs,V=q?.elapsedMs,X=V-Q;if(!j)return;if(C||this.stopped||t.aborted||E.signal.aborted||Y>=O||!u(y)||this.peerLeases.get(y)!==b||y.pc!==j.connection||y.channel!==j.channel||this.latePeerGeneration!==ue||this.options.streamEvent?.id!==Z||this.hls!==oe||this.hls?.media!==ge||l&&this.transferWorker!==Ie||q?.outcome!=="payload"||!Number.isFinite(Q)||Q<0||!Number.isFinite(V)||X<0||!Number.isFinite(R)||!Number.isSafeInteger(L)||L<0||!Number.isSafeInteger(q.receivedBytes)||L>q.receivedBytes||X>=Wr){Ee(y);return}if(!L)return;let de=j.flow.record({freshBytes:L,startAt:R+Q,endAt:Y});if(!de)return;this.peerSelection.observe(de),this.peerFlow.verifiedShortBatches=Oe(this.peerFlow.verifiedShortBatches),this.peerFlow.verifiedShortBytes=Math.min(Number.MAX_SAFE_INTEGER,this.peerFlow.verifiedShortBytes+de.bytes),this.peerFlow.lastVerifiedShortBatch={bytes:de.bytes,spanMs:de.flowMs};let J=this.#J(y);J.flows.push({value:Math.min(1e6,de.bytes/de.flowMs),flowMs:de.flowMs,at:Y}),J.flows.length>Xn&&J.flows.shift()},se=(y,E)=>{let R=y?.verified==null?0:Math.max(0,y.verified-ne);return y?.verified!=null&&(ne=Math.max(ne,y.verified)),this.multiHolder.unusedBytes+=E-R,R},et=I(),St=0,Et=0,Ut=y=>(y!==null&&(clearTimeout(y),this.timers.delete(y)),null),Re=y=>{if(!C){C=!0,Ke.clear(),z=Ut(z),ee=Ut(ee);for(let E of[...M.values(),...H])E.abort();te?.(),r.onDeadline=null,t.removeEventListener("abort",tt),A.free(),S(y)}},tt=()=>Re(null);t.addEventListener("abort",tt,{once:!0});let Ce=(y,E,R,q=Ve)=>{if(C)return;let L=j=>{if(!C){if(r.currentValid&&!r.currentValid()||(l||r.peerOnly)&&I()>=O)return Re(null);j?q(j):Re(null)}};try{let j=_(y,E,R);j?.then?j.then(L,()=>Re(null)):L(j)}catch{Re(null)}},Gr=(y,E)=>{if(y.t==="request"){let R=w.get(y.peer),q=new AbortController;M.set(y.peer,q);let[L,j]=P(y.range),Y=I(),Q=Math.max(1,T-Y),V=null,X=-1/0;Et+=1,p.get(R).refresh&&(p.get(R).refreshStartedAt??=I(),p.get(R).state.probeAt=I());let de=J=>{let re=I();C||M.get(y.peer)!==q||re-XA.progress(le,y.peer,J)))};R.request(s,Q,{signal:q.signal,expectedSize:j-L,onProgress:de,range:{start:y.range.start,end:y.range.end,objectSize:i.size},onResult:J=>{V=J,J.outcome!=="payload"&&Ee(R),this.#we(e,R,Q,J,y.range,a)}}).then(J=>{M.get(y.peer)===q&&M.delete(y.peer),St=Math.max(St,I()-Y),!C&&(V?.firstByteMs!==null&&V?.elapsedMs!==null&&V?.receivedBytes&&(V.elapsedMs-V.firstByteMs>=Wr&&V.receivedBytes>=Kr&&Ee(R),this.peerSelection.observe({firstByteMs:V.firstByteMs,bytes:V.receivedBytes,flowMs:V.elapsedMs-V.firstByteMs})),J?(this.#T(R,I()-Y,J.byteLength),Ce("delivered",{source:y.peer,p:[y.range.start,y.range.end],bytes:J.byteLength},re=>A.delivered(re,y.peer,y.range,J),re=>{let le=se(re,J.byteLength);re.commands.some(ie=>ie.t==="fail"||["ban","cancel","abandon"].includes(ie.t)&&ie.peer===y.peer)?Ee(R):Dt(R,q,Y,V,le),this.multiHolder.peerBytes+=le,le>0&&B.set(R.pc,(B.get(R.pc)??0)+le);let pe=V?.elapsedMs-V?.firstByteMs;le>0&&p.get(R).refresh&&V?.receivedBytes>=Kr&&Number.isFinite(pe)&&pe>=0&&peA.failed(re,y.peer))))},()=>{Ee(R),C||Ce("failed",{source:y.peer},J=>A.failed(J,y.peer))})}else if(y.t==="origin"){if(r.peerOnly){this.multiHolder.failed+=1,Re(null);return}te??=this.#Z(s);let R=new AbortController,[q,L]=P(y.range),j=I(),Y=null,Q=X=>{Y=X,this.originRangeOutcomes[X.outcome]=Oe(this.originRangeOutcomes[X.outcome])};H.add(R),this.multiHolder.originRanges+=1;let V=()=>{this.originsWithoutRanges.has(c)||(this.originsWithoutRanges.add(c),this.multiHolder.originRangesIgnored+=1)};(r.origin?.Loader?Vi(r.origin,e,q,L,{signal:R.signal,onIgnored:V,onResult:Q}):$i(e,q,L,{signal:R.signal,onIgnored:V,onResult:Q})).then(X=>{if(H.delete(R),this.options.traceRequests&&this.#e({k:"origin",load:k,at:this.#s(j),ms:Math.round(I()-j),ranged:!0,range:[y.range.start,y.range.end],outcome:Y?.outcome??(X?"payload":C?"abort":"none"),httpStatus:Y?.httpStatus??null,bytes:X?.byteLength??null}),C)return;let de=[y.range.start,y.range.end];if(!X)return Ce("failed",{source:"origin"},J=>A.failed(J,"origin"));this.#Ke(e,I()-j,X.byteLength,i.size),this.counters.bytesFromOrigin+=X.byteLength,Ce("delivered",{source:"origin",p:de,bytes:X.byteLength},J=>A.delivered(J,"origin",y.range,X),J=>{let re=se(J,X.byteLength);this.multiHolder.originBytes+=re,$+=re,Ve(J)})})}else if(y.t==="cancel"||y.t==="abandon"){Ee(w.get(y.peer));let R=M.get(y.peer);y.t==="abandon"&&(this.multiHolder.abandoned+=1,R&&D.add(R)),R?.abort(y.t==="abandon"?at.ABANDON_REASON:void 0)}else if(y.t==="ban"){let R=w.get(y.peer);Ee(R),this.multiHolder.bans+=1,this.counters.peerCorrupt+=1,this.banned.add(R.pubkey),R.close("integrity")}else if(y.t==="deliver"){this.multiHolder.delivered+=1,this.multiHolderTimings.push([I()-et,St,Et]),this.multiHolderTimings.length>128&&this.multiHolderTimings.shift();let R=E.bytes.byteOffset===0&&E.bytes.byteLength===E.bytes.buffer.byteLength?E.bytes:E.bytes.slice();Re(i.expiresAt<=Math.floor(Date.now()/1e3)?null:{key:s,bytes:R,discoveryContext:o,multi:!0,peerBytes:Math.max(0,i.size-$),contributions:[...B].map(([q,L])=>({connection:q,bytes:L})),shortRefreshes:[...U].map(([q,L])=>({connection:q,at:L}))})}else y.t==="fail"&&(this.multiHolder.failed+=1,Re(null))},Ve=y=>{if(!C){if(!y)return Re(null);for(let E of y.commands)if(Gr(E,y),C)return;z=Ut(z),y.next!==null&&(z=this.#h(Math.max(0,y.next-I()),()=>{z=null,Ce("tick",{},E=>A.tick(E))}))}};r.onDeadline=()=>C?!1:(Ce("tick",{},y=>A.tick(y)),!C&&ee===null&&(ee=this.#h(Math.max(0,r.limit+r.originReserveMs-I()),()=>{ee=null,Re(null)})),!0);let Yr=[...p.values()].some(y=>y.refresh||y.firstByteMs===null)?null:this.peerSelection.firstByteMs(),ir=[...w].filter(([,y])=>p.get(y).rate===null).map(([y])=>y),Zr={peers:N,origin:x,sharedFirstByteMs:Yr,sharedRate:this.peerSelection.rate(),probePeers:ir};Ce("start",this.options.traceRequests?{size:i.size,pieces:i.pieces.length,pieceSize:F,deadline:T-W,maxHolders:this.options.maxHoldersPerObject,originReserveMs:0,...r.peerOnly?{peerOnly:!0}:{},...structuredClone(Zr),holders:[...w].map(([y,E])=>[y,this.#U(E.pubkey)])}:null,y=>A.start(y,Zr),y=>{y?.late&&(this.multiHolder.late+=1),Ve(y)})})}finally{v()}}#Je(e,t,r,s,i){let o=new AbortController,a=()=>o.abort(e.reason);e.aborted?a():e.addEventListener("abort",a,{once:!0});let l=[],c=this.peerSelection.rate(),u=null,d={abandoned:!1,signal:o.signal},f=()=>{d.abandoned||o.signal.aborted||(d.abandoned=!0,o.abort(at.ABANDON_REASON))},g=null;if(i!==null){let m=c?s.deadline-r/c:-1/0;g=setTimeout(()=>{u===null&&f()},Math.max(bl,i*3,m-I()))}let p=m=>{let b=l.at(-1);if(!b)return null;let v=l[0];for(let w of l)if(w[0]<=b[0]-m)v=w;else break;return b[0]-v[0]>=150?{bytes:b[1]-v[1],ms:b[0]-v[0]}:null};return d.progress=(m,b,v)=>{let w=I();if(u===null&&(u=Number.isFinite(v)?v:w-t),l.push([w,m]),l.length>256&&l.shift(),w-ts.deadline)&&f()},d.observation=()=>{let m=l.length?l.at(-1)[0]-l[0][0]:0,b=p(Math.max(300,m/2));return{firstByteMs:u,bytes:b?.bytes??0,flowMs:b?.ms??0,totalFlowMs:m}},d.done=()=>{clearTimeout(g),e.removeEventListener("abort",a)},d}#T(e,t,r){this.peerSelection.record(e,t,r),e.closed&&this.peerSelection.forget(e)}#we(e,t,r,s,i=null,o=null){try{if(!no.includes(s.outcome))return;this.#Ve(t,s);let a=f=>Number.isFinite(f)&&f>=0?f:null,l=f=>Number.isSafeInteger(f)&&f>=0?f:null,c=null,u=null;try{c=l(e?.frag?.cc)}catch{}try{u=l(e?.frag?.level)}catch{}let d={atMs:Math.max(0,Math.round(I()-this.transportStartedAt)),id:this.transportConnections.get(t.pc)?.id||0,holder:this.#U(t.pubkey),cc:c,level:u,remainingMs:a(r),outcome:s.outcome,elapsedMs:a(s.elapsedMs),timeoutMs:a(s.timeoutMs),expectedBytes:l(s.expectedBytes),receivedBytes:l(s.receivedBytes),firstByteMs:a(s.firstByteMs),metadataReceived:s.metadataReceived===!0,draining:s.draining===!0,closeReason:$r["link-close"].includes(s.closeReason)?s.closeReason:null};this.peerRequestCounters[s.outcome]=Oe(this.peerRequestCounters[s.outcome]),this.peerRequestRecords.length===64&&(this.peerRequestRecords.shift(),this.peerRequestDropped=Oe(this.peerRequestDropped)),this.peerRequestRecords.push(d),this.#e({k:"request",load:o,at:this.#s(),range:i?[i.start,i.end]:null,...d})}catch{}}#Qe(e){let t=this;class r{static relayswarmShadow=!0;constructor(i){this.inner=new e(i)}get stats(){return this.inner.stats}get context(){return this.inner.context}load(i,o,a){t.#Y(i);let l=t.#et(i);if(this.race=l,!l)return this.inner.load(i,o,a);let c=[],u=0,d=l.sampled||t.#xe(),f={...a,onProgress:a.onProgress?(g,p,m,b)=>{try{m?.byteLength&&(d&&c.push(m.slice(0)),u+=m.byteLength)}catch{}a.onProgress(g,p,m,b)}:void 0,onSuccess:(g,p,m,b)=>{let v=Vr(p),w=null,T=0;try{let O=g?.data;O?.byteLength?(d&&(w=O.slice(0)),T=O.byteLength):u&&(d&&(w=r.join(c)),T=u)}catch{w=null,T=0}l.originSucceeded=!0,a.onSuccess(g,p,m,b),t.#B(b,v),T?t.#n("origin-loaded",()=>t.#rt(l,w,T)):t.#n("origin-empty",()=>t.#z(l))},onError:(...g)=>{t.#n("origin-error",()=>t.#z(l)),a.onError(...g)},onTimeout:(...g)=>{t.#n("origin-timeout",()=>t.#z(l)),a.onTimeout(...g)}};return a.onAbort&&(f.onAbort=(...g)=>{t.#n("origin-abort",()=>t.#z(l)),a.onAbort(...g)}),this.inner.load(i,o,f)}abort(){return this.race&&t.#z(this.race),this.inner.abort()}destroy(){return this.race&&!this.race.originSucceeded&&!this.race.originDone&&t.#z(this.race),this.inner.destroy()}getCacheAge(){return this.inner.getCacheAge?.()??null}getResponseHeader(i){return this.inner.getResponseHeader?.(i)??null}static join(i){let o=i.reduce((c,u)=>c+u.byteLength,0),a=new Uint8Array(o),l=0;for(let c of i)a.set(new Uint8Array(c),l),l+=c.byteLength;return a.buffer}}return r}#et(e){try{if(this.stopped||this.races.size>=this.options.maxConcurrentRaces)return null;let t=e?.frag;if(!t||t.sn==="initSegment"||e.part&&!this.options.swarmParts)return this.counters.skipped+=1,null;let r=e.url||t.url,s=(this.options.segmentKey||to)(r,e);if(typeof s!="string"||!s)return this.counters.skipped+=1,null;let i=e.rangeEnd?`#${e.rangeStart||0}-${e.rangeEnd}`:"",o={controller:new AbortController,t0:I(),keyText:`${this.options.swarmId} +${s}${i}`,key:null,sampled:Math.random()this.#tt(o)),o}catch(t){return this.#o("begin-race",t),null}}async#tt(e){if(e.keyPromise=Pt(eo.encode(e.keyText)),e.key=await e.keyPromise,this.stopped)return;if(!e.sampled||!this.options.serveOnCellular&&Ht())return e.peerDone=!0,e.skipPeers=!0,this.#n("settle",()=>this.#te(e));let t=e.t0+this.options.lateWindowMs,r=new Set,s=e.peersAtStart>0;for(;!this.stopped&&!e.settled&&!e.originFailed&&I()0,this.#n("settle",()=>this.#te(e))}#ee(e,t,r){return new Promise(s=>{let i=null,o=l=>{l&&!l.includes(e)||(clearTimeout(i),r?.removeEventListener("abort",a),this.haveWaiters.delete(o),s())},a=()=>o();if(r?.aborted)return s();r?.addEventListener("abort",a,{once:!0}),i=setTimeout(o,Math.max(0,Math.min(t,1e3))),this.haveWaiters.add(o)})}async#rt(e,t,r){if(this.stopped||e.originFailed)return;let s=t&&new Uint8Array(t),i=I();this.counters.originLoaded+=1,this.counters.bytesFromOrigin+=r,e.originBytes=r,We(this.originLatencySamples,i-e.t0),e.sampled&&(e.originDigest=await Pt(s)),e.originDone=!0,await e.keyPromise,!this.stopped&&(s&&this.#L(e.key,s),this.#n("settle",()=>this.#te(e)))}#z(e){e.settled||e.originDone||(e.controller.abort(),e.originDone=!0,e.originFailed=!0,this.#n("settle",()=>this.#te(e)))}async#te(e){if(e.settled||!e.originDone||!e.peerDone)return;e.settled=!0,this.races.delete(e);let t=this.counters;if(e.skipPeers)return void(t.sampledOut+=1);if(e.originFailed){e.peerBytes?t.peerUnverified+=1:t.aborted+=1;return}if(t.sampledOriginBytes+=e.originBytes||0,!e.peerBytes){e.sawPeer?(t.raced+=1,t.peerMiss+=1):t.noPeers+=1;return}if(t.raced+=1,await Pt(e.peerBytes)!==e.originDigest){this.#T(e.peerLink,e.requestMs),t.peerCorrupt+=1,this.banned.add(e.peerLink.pubkey),e.peerLink.close("integrity");return}let s=e.peerAt-e.t0;this.#T(e.peerLink,e.requestMs,e.peerBytes.byteLength),this.firstPeerSegmentAtMs===null&&(this.firstPeerSegmentAtMs=Date.now()-this.startedAt),We(this.peerLatencySamples,s),t.bytesFromPeers+=e.peerBytes.byteLength,s<=this.options.originFallbackMs?(t.peerInTime+=1,t.peerInTimeBytes+=e.peerBytes.byteLength):t.peerLate+=1}#L(e,t){if(!this.#p()||this.held.has(e)||t.byteLength>this.options.maxSegmentBytes)return;this.held.set(e,t),this.heldBytes+=t.byteLength;let r=this.#ve(this.options.maxHeldBytes-(this.warmAhead?.snapshot().reservationBytes??0),!1);if(this.#p())for(let s of this.links.values())s.sendHaveChange(this.held.has(e)?[e]:[],r)}#nt(e){let t=this.held.get(e);if(t){this.held.delete(e),this.heldBytes-=t.byteLength,this.warmAhead?.release(e);for(let r of this.links.values())r.sendHaveChange([],[e])}}#ve(e,t=!0){let r=[];for(;this.held.size&&(this.held.size>this.options.maxHeldSegments||this.heldBytes>Math.max(0,e));){let s=this.warmAhead?[...this.held].find(([a])=>!this.warmAhead.pinned(a)):this.held.entries().next().value;if(!s)break;let[i,o]=s;this.held.delete(i),this.heldBytes-=o.byteLength,this.warmAhead?.release(i),r.push(i)}if(t&&r.length)for(let s of this.links.values())s.sendHaveChange([],r);return r}#xe(){return!this.stopped&&!this.disabledReason&&this.options.serve===!0}#p(){return!this.stopped&&!this.disabledReason&&this.options.serve===!0&&this.#H()!==0&&(this.options.serveOnCellular||!Ht())}#H(){let e=this.options.maxUploadBytesPerSession;return!Number.isSafeInteger(e)||e<0?null:Math.max(0,e-this.uploadQuotaBytes)}#Se(){this.warmAhead?.clear();for(let e of this.cachedRaces)e.abort();this.held.clear(),this.heldBytes=0,this.uploadPacer?.recheck();for(let e of this.links.values())e.sendHave([]),e.sendContribution(!1,this.rendition);this.#V()}async#st(e,t,r=null){if(this.uploadPacer)return this.#it(e,t,r);let s=this.admissionChecks.get(e.pubkey)?.ticket??this.admitted.get(e.pubkey)?.ticket;if(this.options.admit&&!await this.#x(e.pubkey,s,"upload"))return this.#y("admission"),e.close("admission"),null;if(e.closed)return null;let i=this.held.get(t);if(!i)return this.#y("not-held"),null;let o=i.byteLength;if(r){let u=xt(i.byteLength),d=r.start*u,f=Math.min(r.end*u,i.byteLength);if(!(da)return this.#y("session-allowance"),null;let l=[...this.links.values()].filter(u=>u!==e&&(u.outboundInFlight>0||Date.now()-u.lastServedAt<3e4)).length;if(Date.now()-e.lastServedAt>=3e4&&l>=this.options.maxUploadPeers)return this.#y("peer-limit"),null;let c=(I()-this.uploadRefilledAt)/1e3;if(this.uploadRefilledAt=I(),this.uploadTokens=Math.min(this.options.maxUploadBytesPerSecond*2,this.uploadTokens+c*this.options.maxUploadBytesPerSecond),this.uploadTokensthis.options.reserveUploadBytes(o,{signal:d}),this.lifecycle.signal,this.options.admissionTimeoutMs)===!0}catch{this.#o("upload-reservation")}if(!u||this.stopped||e.closed||this.options.serve!==!0||!this.options.serveOnCellular&&Ht())return u||(this.uploadQuotaBytes-=o),this.#y(u?"reservation-inactive":"reservation-refused"),null}if(this.counters.bytesUploaded+=o,this.counters.uploadsServed+=1,this.options.testHooks?.corruptUploads){let u=i.slice();return u[u.length>>1]^=255,u}return i}#y(e){this.counters.uploadsRefused+=1,this.uploadRefusalCounters[e]=Oe(this.uploadRefusalCounters[e])}#Ee(){let e=I(),t=Math.max(0,e-this.uploadRefilledAt)/1e3;this.uploadRefilledAt=e,this.uploadTokens=Math.min(this.options.maxUploadBytesPerSecond*2,this.uploadTokens+t*this.options.maxUploadBytesPerSecond)}#Ae(e,t){let r=this.held.get(e)?.byteLength;if(!Number.isSafeInteger(r)||r<1)return null;if(!t)return{key:e,size:r,charge:r,range:null};let s=xt(r);if(!Number.isSafeInteger(t.start)||!Number.isSafeInteger(t.end)||t.start<0||t.end<=t.start||t.end>Math.ceil(r/s))return null;let i=Math.min(t.end*s,r)-t.start*s;return{key:e,size:r,charge:i,range:{start:t.start,end:t.end}}}#ke(e,t=!1){if(this.stopped||this.disabledReason||!this.options.serve||e.link.closed||this.links.get(e.link.pubkey)!==e.link||!this.options.serveOnCellular&&Ht()||this.banned.has(e.link.pubkey))return!1;let r=this.#Ae(e.key,e.range);if(!r||r.size!==e.size||r.charge!==e.charge)return!1;let s=this.#H();if(!t&&s!==null&&e.charge>s)return!1;let i=[...this.links.values()].filter(o=>o!==e.link&&(o.outboundInFlight>0||Date.now()-o.lastServedAt<3e4)).length;return Date.now()-e.link.lastServedAt<3e4||ii.active&&!c.aborted&&this.#ke(i,o);try{if(!u())return null;let d=this.admissionChecks.get(e.pubkey)?.ticket??this.admitted.get(e.pubkey)?.ticket;if(this.options.admit&&!await lt(()=>this.#x(e.pubkey,d,"upload"),c,this.options.admissionTimeoutMs))return this.#y("admission"),e.close("admission"),null;if(!u())return null;if(this.uploadQuotaBytes+=i.charge,o=!0,this.options.reserveUploadBytes){try{a=await lt(g=>this.options.reserveUploadBytes(i.charge,{signal:g}),c,this.options.admissionTimeoutMs)===!0}catch{this.#o("upload-reservation")}if(a!==!0)return this.#y("reservation-refused"),null}else a=!0;if(!u()||this.options.admit&&this.admitted.get(e.pubkey)?.ticket!==d)return this.#y("reservation-inactive"),null;let f=this.held.get(t);if(!f||f.byteLength!==i.size)return this.#y("not-held"),null;if(this.counters.bytesUploaded+=i.charge,this.counters.uploadsServed++,l=!0,this.options.testHooks?.corruptUploads){let g=f.slice();return g[g.length>>1]^=255,g}return f}catch{return null}finally{o&&a===!1&&(this.uploadQuotaBytes-=i.charge),o&&this.#H()===0&&this.#Se(),this.uploadPacer.finish(i,l)}}async#ot(){this.coreState="loading";try{let e=await qi(this.options.coreWasm,{onFailure:r=>this.#le(r)});if(this.stopped)return;this.core=e,this.coreVerifier=e.verifier,this.peerSelection.order===0&&(this.peerSelection=e.peerSelection());let t=this.discovery;t.contexts.size===0&&t.candidates.size===0&&!t.window&&(this.discovery=e.neighbourDiscovery(),Object.assign(this.discovery.counters,t.counters)),this.coreState="ready",this.options.transferWorkerUrl!==void 0&&this.#at(e)}catch(e){this.coreState="failed",this.options.transferWorkerUrl!==void 0&&(this.transferWorkerState="failed",this.transferWorkerReason="core-failed"),this.#o("core",e)}}async#at(e){this.transferWorkerState="loading";try{let t=this.options.WorkerImpl,r=await Wi({module:e.module,workerUrl:this.options.transferWorkerUrl,workerFactory:t?(s,i)=>new t(s,i):void 0,signal:this.lifecycle.signal,maxSegmentBytes:Math.min(32*1024*1024,this.options.maxSegmentBytes),onFailure:s=>this.#Me(s)});if(this.stopped||this.core!==e||e.retired){r.stop();return}this.transferWorker=r,this.transferWorkerState="ready"}catch(t){this.stopped||this.#Me(t)}}#Me(e){this.stopped||this.transferWorkerState==="failed"||(this.transferWorkerState="failed",this.transferWorkerReason=typeof e?.code=="string"?e.code:"worker-failed",this.#o("transfer-worker",e))}#le(e){let t=this.#A();this.core?.retire(),this.transferWorker?.stop(),this.options.transferWorkerUrl!==void 0&&(this.transferWorkerState="failed",this.transferWorkerReason="core-failed"),this.coreVerifier=null,this.coreState="failed",this.coreFallbacks+=1,this.#o("core",e),t&&this.#V()}#A(){return this.options.multiHolder===!0&&this.options.mode==="peer-first"&&!!this.core&&!this.core.retired&&this.coreLinks.js===0}#lt(e){if(this.core&&!this.core.retired)try{let t=this.core.peerLink(e);return this.coreLinks.wasm+=1,t}catch(t){this.#le(t)}return this.coreLinks.js+=1,new at(e)}#ce(e,t){if(this.coreVerifier)try{let r=this.coreVerifier.verifySegmentCommitment(e,t);return this.coreDecided.wasm+=1,r}catch(r){this.#le(r)}return this.coreDecided.js+=1,Ii(e,t)}async#ct(){let e=this.options.secretKey||Yt();if(this.pool=new Or(this.options.relays,{label:"hls-swarm",WebSocketImpl:this.options.WebSocketImpl||globalThis.WebSocket,reconnect:!0}),await Promise.all([this.pool.connect(),this.coreWait]),this.stopped)return this.pool.close();this.session=new Ir({pool:this.pool,swarmId:this.options.swarmId,secretKey:e,maxEventAgeSeconds:60}),this.session.onPresence(t=>this.#n("presence",()=>this.#mt(t))),this.session.onSignal(t=>this.#n("signal",()=>this.#yt(t))),this.session.onError(t=>this.#o("session",t)),this.session.start(),this.#V(),this.#M(this.options.presenceIntervalMs,.3,()=>this.#V())}#V(){if(!(!this.session||this.stopped))try{this.session.announcePresence({role:"viewer",transports:[{type:jr,publicKey:this.session.pubkey,...this.#A()?{obj:2}:{}}],have:this.#p()?[...this.held.keys()].slice(-8):[],open:this.#ut(),...this.#se()?{ticket:this.#se()}:{}}),this.counters.presenceSent+=1;for(let[e,t]of this.renditions){if(t{this.reannounceTimer=null,this.#V()})}#F(e,t){return!e.closed&&e.contribution?.serving&&(e.renditions.get(t)||0)>Date.now()-3e4}#he(e){return![...this.links.values()].some(t=>!this.discovery.stale(e,t.pubkey)&&(this.#F(t,e.rendition)||e.keys.some(r=>t.have.has(r))))}#Re(e){let t=[...this.links.values()].filter(r=>this.#F(r,e.rendition));return t.length>0&&t.every(r=>this.discovery.stale(e,r.pubkey))}#ht(e){return[...this.links.values()].filter(t=>this.#F(t,e.rendition)).every(t=>this.discovery.stale(e,t.pubkey))}#Te(e){return!this.links.has(e.pubkey)&&!this.dials.has(e.pubkey)&&!this.dialChecks.has(e.pubkey)&&!this.#D(e.pubkey)&&(!this.#G()||ye(e.ticket))&&(this.retries.get(e.pubkey)||0)<=this.options.maxRetriesPerPeer}#Le(e){if(this.discovery.spent(e)||this.links.size<2||Date.now()-this.lastEvictionAtDate.now()-r.activityAt<3e4);return oo([...this.links.values()].filter(r=>!t.some(s=>!this.discovery.stale(s,r.pubkey)&&(this.#F(r,s.rendition)||s.keys.some(i=>r.have.has(i))))),{...this.options,banned:this.banned,tier:r=>this.#Ie(r)})}#q(e=this.discovery.window,t=!0){if(!e||!this.discovery.end(e))return;clearTimeout(e.timer),this.timers.delete(e.timer);let r=e.attempt,s=r?.dial;t&&s&&s.discovery===r&&s.negotiation===r.negotiation&&this.dials.get(s.pubkey)===s&&(s.discovery=null,this.#m(s,"superseded"))}#j(e=!0){let t=this.discovery.window;t&&(!this.discovery.live(t)||!this.discovery.current(t.context)||e&&t.attempt&&!this.discovery.valid(t.attempt))&&(this.discovery.counters.expired++,this.#q(t))}#re(){if(this.stopped||this.options.mode!=="peer-first"||(this.#j(),!this.#ne()))return;for(let i of this.discovery.contexts.values())this.discovery.rearm(i,()=>this.#ht(i));let e=this.links.size+this.dials.sizethis.#Te(i),i=>this.#he(i)&&(e||this.discovery.reserved()||!!this.#Le(i)),e);if(!t)return;let r=this.discovery.begin(t);if(!r)return;this.#Re(t.context)&&this.discovery.counters.staleHolder++;let s=r.window;s.timer||(s.timer=this.#h(Math.max(0,s.expiresAt-Date.now()),()=>this.#q(s))),this.#n("discovery",()=>this.#oe(r.pubkey,r))}#$(e,t){this.openPeers.set(e,{open:t,at:Date.now()}),this.openPeers.size>64&&this.openPeers.delete(this.openPeers.keys().next().value)}#_e(){let e=Date.now()-6e4;return[...this.openPeers.entries()].filter(([t,r])=>r.open&&r.at>=e&&!this.banned.has(t)).sort((t,r)=>r[1].at-t[1].at).map(([t])=>t)}#Oe(){return oo(this.links.values(),{...this.options,banned:this.banned,tier:e=>this.#Ie(e)})}#Ie(e){if(e.contribution?.serving===!0)return 1;if(!this.#p())return 0;let t=Date.now(),r=2*this.options.presenceIntervalMs;for(let[s,i]of e.announced??[]){if(t-i>r)continue;let o=this.renditions.get(s);if(o!==void 0&&t-o<=3e4)return 2}return 0}#Ce(e,t,r){let s=["Unhelpful","Serving","Consumer"][t];e[`${r}${s}`]++}#ut(){return this.#j(),this.discovery.reserved()?!1:this.#_()||this.links.size>=2&&!!this.#Oe()}#dt(e,t){if(this.discovery.reserved())return null;let r=Number.isSafeInteger(e)&&e>0&&typeof t=="string"&&/^[0-9a-f]{64}$/u.test(t)&&this.held.has(t)&&this.#p();if(e!==0&&!r||this.links.size<2||Date.now()-this.lastEvictionAts!==e).slice(0,this.options.maxReferrals);return r.length&&(this.counters.referralsSent+=r.length),{retryAfterMs:t,referrals:r}}#ue(e,t,r,s={}){try{return this.stopped?!1:(this.session.sendSignal(e,{type:t,transport:jr,requestId:r,payload:s}),this.counters.signalsSent+=1,!0)}catch(i){return this.counters.publishErrors+=1,this.#o("signal-send",i),!1}}#pt(e){return Al(e,this.options)}#gt(e,{retryAfterMs:t,referrals:r}){let s=(this.retries.get(e)||0)+1;s<=this.options.maxRetriesPerPeer&&(this.retries.set(e,s),this.counters.retriesScheduled+=1,this.#h(t+Math.random()*1e3,()=>{if(this.discovery.reserved()){this.cooldowns.delete(e),this.#re();return}if(!(this.links.has(e)||this.dials.has(e)||this.banned.has(e)||!this.#_()))return this.cooldowns.delete(e),this.#oe(e)}));for(let i of r)if(i!==this.session?.pubkey&&!(this.#G()&&!this.admitted.has(i))&&!(this.links.has(i)||this.dials.has(i)||this.#D(i)||!this.#_())){if([...this.dials.values()].filter(o=>o.outgoing).length>=this.options.maxDialsInFlight)break;this.counters.referralsFollowed+=1,this.#n("referral",()=>this.#oe(i))}}#_(){return this.#j(),this.links.size+this.dials.size+(this.discovery.reserved()?1:0)e.outgoing).length+this.dialChecks.sizeDate.now()}#G(){return typeof this.options.admit=="function"}#se(){return ye(this.options.ticket)?this.options.ticket:void 0}async#x(e,t,r="other"){if(this.stopped)return!1;if(!this.#G())return!0;if(!ye(t))return this.counters.admitRefused+=1,!1;let s=this.admissionChecks.get(e);if(s)return s.ticket===t?s.promise:!1;if(this.admissionChecks.size>=16)return!1;let i={ticket:t,promise:null};return i.promise=(async()=>{let o=!1;try{o=await lt(a=>{try{let l=so.includes(r)?r:"other";this.admissionCallCounters[l]=Oe(this.admissionCallCounters[l])}catch{}return this.options.admit(e,t,{signal:a})},this.lifecycle.signal,this.options.admissionTimeoutMs)===!0}catch(a){this.#o("admit",a)}if(this.stopped||this.admissionChecks.get(e)!==i)return!1;if(o){let a=this.admitted.get(e)?.candidateTicket;this.admitted.set(e,{ticket:t,...ye(a)&&a!==t?{candidateTicket:a}:{}}),this.admitted.size>256&&this.admitted.delete(this.admitted.keys().next().value)}else{let a=this.admitted.get(e);a?.ticket===t?this.admitted.delete(e):a?.candidateTicket===t&&delete a.candidateTicket,this.counters.admitRefused+=1}return o})().finally(()=>{if(this.admissionChecks.get(e)!==i)return;this.admissionChecks.delete(e);let o=i.latestPresence;o&&!this.stopped&&(this.links.has(e)||this.dials.has(e))&&this.#n("admission-refresh",async()=>{await this.#x(e,o.ticket,"refresh")&&o.open!==null&&this.#$(e,o.open)})}),this.admissionChecks.set(e,i),i.promise}#Ne(e,t){t===2&&(this.remoteFraming.delete(e),this.remoteFraming.set(e,2),this.remoteFraming.size>1024&&this.remoteFraming.delete(this.remoteFraming.keys().next().value))}async#mt({from:e,payload:t}){if(this.stopped||t.role!=="viewer")return;let r=t.transports.find(l=>l.type===jr);if(!r)return;this.remoteFraming.delete(e),this.remoteFraming.set(e,r.obj??1),this.remoteFraming.size>1024&&this.remoteFraming.delete(this.remoteFraming.keys().next().value),this.options.mode==="peer-first"&&(this.discovery.hint(e,t.have,t.ticket),this.#re());let s=this.links.has(e)||this.dials.has(e),i=this.admitted.get(e);i&&ye(t.ticket)&&t.ticket!==i.ticket&&(i.candidateTicket=t.ticket);let o=!this.#G()||i&&i.ticket===t.ticket;if(s&&o){t.open!==null&&this.#$(e,t.open),this.#k();return}if(!s&&(this.#D(e)||!this.#_()||!this.#ne())){o&&t.open!==null&&this.#$(e,t.open);return}let a=this.admissionChecks.get(e);if(s&&a){ye(t.ticket)&&t.ticket!==a.ticket&&(a.latestPresence={ticket:t.ticket,open:t.open});return}!await this.#x(e,t.ticket,"presence")||this.stopped||(t.open!==null&&this.#$(e,t.open),this.#k(),!(this.links.has(e)||this.dials.has(e)||this.#D(e)||!this.#_())&&this.#h(Math.random()*1500,()=>{if(!(this.links.has(e)||this.dials.has(e)||this.#D(e)||!this.#_())&&this.#ne())return this.#oe(e)}))}#g(e,t,r,s){try{if(!$r[t]?.includes(r))return;let i=this.transportConnections.get(e);if(i?.ended)return;let o=I()-this.transportStartedAt,a={id:i?.id??0,atMs:Number.isFinite(o)?Math.max(0,Math.round(o)):0,event:t,detail:r};Number.isSafeInteger(s)&&s>=0&&s<=256&&(a.candidates=s,a.candidatesCapped=s===256),this.transportCounters[t][r]=Oe(this.transportCounters[t][r]),this.transportRecords.length===64&&(this.transportRecords.shift(),this.transportDropped=Oe(this.transportDropped)),this.transportRecords.push(a)}catch{}}#Pe(e,t,r){try{let s,i=e.localDescription?.sdp;if(typeof i=="string"&&i.length<=256*1024){s=0;for(let o of i.matchAll(/^a=candidate:/gm))if(++s===256)break}this.#g(e,`local-${t}`,r,s)}catch{this.#g(e,`local-${t}`,r)}}#de(e,t,r){this.#g(e,t,r);let s=this.transportConnections.get(e);if(!(!s||s.ended)){s.ended=!0;for(let[i,o]of s.listeners)try{e.removeEventListener?.(i,o)}catch{}s.listeners.length=0}}#He(e){let t=this.options.RTCPeerConnectionImpl||globalThis.RTCPeerConnection,r=new t({iceServers:this.options.iceServers,iceTransportPolicy:this.options.iceTransportPolicy}),s={id:this.transportSequence{try{let c=r[o];this.#g(r,i,$r[i].includes(c)?c:"unknown")}catch{this.#g(r,i,"unknown")}};try{r.addEventListener(a,l),s.listeners.push([a,l]),l()}catch{}}return r}#u(e,t){return!this.stopped&&this.dials.get(e.pubkey)===e&&e.negotiation===t&&!t.controller.signal.aborted&&(!e.discovery||this.discovery.valid(e.discovery))}#ie(e,t=!0){let r=e.negotiation;if(r&&(r.controller.abort(),r.onDataChannel&&e.pc.removeEventListener("datachannel",r.onDataChannel),r.channel&&r.onOpen&&r.channel.removeEventListener("open",r.onOpen),t))try{r.channel?.close()}catch{}}#De(e,t,r){!r&&e.discovery&&(this.#q(e.discovery.window,!1),e.discovery=null),e.negotiation&&(e.negotiation.superseded=!0),this.#ie(e),e.requestId=t,e.outgoing=r;let s={controller:new AbortController,channel:null,ready:!1};return e.negotiation=s,s}#fe(e,t,r){let s=(e.operations??Promise.resolve()).then(()=>{if(this.#u(e,t))return r()});return e.operations=s.catch(()=>{}),s}#Ue(e,t,r){if(t.channel!==r){if(!this.#u(e,t)||t.channel){try{r.close()}catch{}return}t.channel=r,t.onOpen=()=>{t.ready&&this.#n("link-open",()=>this.#bt(e,t,r))},r.addEventListener("open",t.onOpen),r.readyState==="open"&&t.onOpen()}}#ze(e,t){this.#u(e,t)&&(t.ready=!0,t.channel?.readyState==="open"&&t.onOpen())}async#oe(e,t=null){if(this.stopped||this.links.has(e)||this.dials.has(e)||this.dialChecks.has(e)||this.#D(e)||!(t?this.discovery.valid(t):this.#_())||!this.#ne()){t&&this.discovery.abandoned(t);return}this.dialChecks.add(e);try{if(!await this.#x(e,t?t.ticket:this.admitted.get(e)?.candidateTicket??this.admitted.get(e)?.ticket,"dialStart")){t&&(this.discovery.abandoned(t),this.cooldowns.set(e,Date.now()+6e4));return}}finally{this.dialChecks.delete(e)}if(this.stopped||this.links.has(e)||this.dials.has(e)||this.#D(e)||[...this.dials.values()].filter(a=>a.outgoing).length>=this.options.maxDialsInFlight||(t?!this.discovery.valid(t)||!this.#he(t.window.context):!this.#_())){t&&this.discovery.abandoned(t);return}if(t&&this.links.size+this.dials.size>=this.options.maxPeers){let a=this.#Le(t.window.context),l=a?.link;if(!l||!this.discovery.replaced(t,l.pubkey)){this.discovery.abandoned(t);return}this.lastEvictionAt=Date.now(),this.counters.evicted++,this.#Ce(this.discovery.counters,a.tier,"victim"),this.cooldowns.set(l.pubkey,t.window.expiresAt),l.close("rotation")}let r=this.#He(!0),s=Sl(),i={pubkey:e,pc:r,startedAt:I(),offerSentAt:0};t&&(i.discovery=t,this.discovery.allocated(t,i)),this.dials.set(e,i);let o=this.#De(i,s,!0);t&&(t.negotiation=o),this.counters.dialsStarted+=1,i.timer=this.#h(t?Math.min(this.options.dialTimeoutMs,Math.max(0,t.window.expiresAt-Date.now())):this.options.dialTimeoutMs,()=>this.#m(i,"timeout"));try{this.#Ue(i,o,r.createDataChannel("relayswarm",{ordered:!0})),await this.#fe(i,o,async()=>{let a=await r.createOffer();if(!this.#u(i,o)||(await r.setLocalDescription(a),!this.#u(i,o))||(await io(r,1200,o.controller.signal,u=>{i.negotiation===o&&!o.superseded&&this.#Pe(r,"offer",u)}),!this.#u(i,o)))return;if(!await this.#x(e,this.admitted.get(e)?.candidateTicket??this.admitted.get(e)?.ticket,"offerBeforeSend")){this.#u(i,o)&&this.#m(i,"failed",0,"admission");return}if(!this.#u(i,o))return;i.offerSentAt=I();let l=this.#se(),c=this.#ue(e,"offer",s,{sdp:r.localDescription.sdp,peers:this.links.size,...this.#A()?{obj:2}:{},...i.discovery?{requestedKey:i.discovery.key}:{},...l?{ticket:l}:{}});this.#g(r,c?"signal-send":"signal-failed","offer"),c||this.#m(i,"failed")})}catch(a){if(!this.#u(i,o))return;this.#o("dial",a),this.#m(i,"failed")}}#m(e,t,r=0,s=t){if(this.dials.get(e.pubkey)!==e)return;this.dials.delete(e.pubkey),this.discovery.failed(e),this.#ie(e),clearTimeout(e.timer),this.timers.delete(e.timer),this.#de(e.pc,"dial-end",s);try{e.pc.close()}catch{}if(t==="timeout"?this.counters.dialsTimedOut+=1:t==="rejected"?this.counters.dialsRejected+=1:t!=="superseded"&&(this.counters.dialsFailed+=1),t==="superseded")return;let i=t==="rejected"?3e4:6e4;this.cooldowns.set(e.pubkey,Date.now()+(r>0?r:i)),this.#re()}async#yt({from:e,payload:t}){if(this.stopped||t.transport!==jr)return;let r=typeof t.payload?.sdp=="string"?t.payload.sdp:"";if(t.type==="answer"){let d=this.dials.get(e);if(!d?.outgoing||d.requestId!==t.requestId||!r)return;let f=d.negotiation;if(f.answerPending)return;if(this.#g(d.pc,"answer-received","authenticated"),!await this.#x(e,ye(t.payload.ticket)?t.payload.ticket:null,"answerIncoming")){this.#u(d,f)&&this.#m(d,"failed",0,"admission");return}if(!this.#u(d,f)||!d.outgoing||d.requestId!==t.requestId||f.answerPending)return;f.answerPending=!0,this.#g(d.pc,"answer-admitted","accepted"),d.answerAt=I();try{await this.#fe(d,f,async()=>{await d.pc.setRemoteDescription({type:"answer",sdp:r}),this.#u(d,f)&&(this.#g(d.pc,"remote-installed","answer"),this.#Ne(e,t.payload.obj),this.#ze(d,f))})}catch(g){this.#u(d,f)&&(this.#o("answer",g),this.#m(d,"failed"))}return}if(t.type==="reject"){let d=this.dials.get(e);if(!d?.outgoing||d.requestId!==t.requestId)return;let f=this.#pt(t.payload);this.#m(d,"rejected",f.retryAfterMs),this.#$(e,!1),this.#gt(e,f);return}if(t.type!=="offer"||!r||(this.#j(),this.discovery.suppresses(e))||this.banned.has(e)||this.links.has(e))return;let s=`${e}:${t.requestId}`,i=this.dials.get(e);if(i&&!i.outgoing&&i.requestId===t.requestId||this.receivedOffers.has(s)||(this.#g(this.dials.get(e)?.pc,"offer-received","authenticated"),!await this.#x(e,ye(t.payload.ticket)?t.payload.ticket:null,"offerIncoming")||this.stopped||this.links.has(e))||(this.#j(),this.discovery.suppresses(e)))return;let o=this.dials.get(e);if(o&&!o.outgoing&&o.requestId===t.requestId||this.receivedOffers.has(s))return;this.receivedOffers.add(s),this.receivedOffers.size>256&&this.receivedOffers.delete(this.receivedOffers.values().next().value);let a,l=!1;if(o?.outgoing){if(o.negotiation.answerPending||this.session.pubkeythis.options.maxPeers||!["new","connecting"].includes(o.pc.connectionState)||!["new","checking"].includes(o.pc.iceConnectionState)||!["stable","have-local-offer"].includes(o.pc.signalingState)){this.#m(o,"failed");return}a=o,l=!0}else{if(o&&this.#m(o,"superseded"),!this.#_()&&!this.#dt(t.payload?.peers,t.payload?.requestedKey)){this.counters.offersRefused+=1,this.counters.evictionsUnavailable+=1,this.#ue(e,"reject",t.requestId,this.#ft(e));return}let d=this.#He(!1);a={pubkey:e,pc:d,startedAt:I(),offerSentAt:I()},this.dials.set(e,a),a.timer=this.#h(this.options.dialTimeoutMs,()=>this.#m(a,"timeout"))}let c=a.pc,u=this.#De(a,t.requestId,!1);l&&this.#g(c,"negotiation","glare-yield"),this.#g(c,"offer-admitted","accepted"),u.onDataChannel=d=>this.#Ue(a,u,d.channel),c.addEventListener("datachannel",u.onDataChannel);try{await this.#fe(a,u,async()=>{if(l){if(!await this.#x(e,ye(t.payload.ticket)?t.payload.ticket:null,"glareBeforeRollback")){this.#u(a,u)&&this.#m(a,"failed",0,"admission");return}if(!this.#u(a,u))return;if(this.links.size+this.dials.size>this.options.maxPeers||!["new","connecting"].includes(c.connectionState)||!["new","checking"].includes(c.iceConnectionState))throw new Error("Pending connection unavailable.");if(c.signalingState==="have-local-offer"&&(await c.setLocalDescription({type:"rollback"}),!this.#u(a,u)))return;if(this.links.size+this.dials.size>this.options.maxPeers||c.signalingState!=="stable"||!["new","connecting"].includes(c.connectionState)||!["new","checking"].includes(c.iceConnectionState))throw new Error("Pending negotiation unavailable.");if(!await this.#x(e,ye(t.payload.ticket)?t.payload.ticket:null,"glareAfterRollback")){this.#u(a,u)&&this.#m(a,"failed",0,"admission");return}if(!this.#u(a,u))return;if(this.links.size+this.dials.size>this.options.maxPeers||c.signalingState!=="stable"||!["new","connecting"].includes(c.connectionState)||!["new","checking"].includes(c.iceConnectionState))throw new Error("Pending negotiation unavailable.")}if(await c.setRemoteDescription({type:"offer",sdp:r}),!this.#u(a,u))return;this.#g(c,"remote-installed","offer");let d=await c.createAnswer();if(!this.#u(a,u)||(await c.setLocalDescription(d),!this.#u(a,u))||(await io(c,1200,u.controller.signal,p=>{a.negotiation===u&&!u.superseded&&this.#Pe(c,"answer",p)}),!this.#u(a,u)))return;if(!await this.#x(e,ye(t.payload.ticket)?t.payload.ticket:null,"answerBeforeSend")){this.#u(a,u)&&this.#m(a,"failed",0,"admission");return}if(!this.#u(a,u))return;let f=this.#se(),g=this.#ue(e,"answer",t.requestId,{sdp:c.localDescription.sdp,...this.#A()?{obj:2}:{},...f?{ticket:f}:{}});this.#g(c,g?"signal-send":"signal-failed","answer"),g?(this.#Ne(e,t.payload.obj),this.counters.offersAccepted+=1,this.#ze(a,u)):this.#m(a,"failed")})}catch(d){this.#u(a,u)&&(this.#o("offer",d),this.#m(a,"failed"))}}async#bt(e,t,r){if(!this.#u(e,t)||t.channel!==r||!t.ready){if(this.links.get(e.pubkey)?.channel!==r)try{r.close()}catch{}return}this.#g(e.pc,"channel-open","accepted"),this.#ie(e,!1);let s=a=>{if(a.channel!==r)try{a.channel.close()}catch{}};e.pc.addEventListener("datachannel",s),this.dials.delete(e.pubkey),e.discovery&&(this.discovery.counters.opened++,this.#q(e.discovery.window,!1),e.discovery=null),clearTimeout(e.timer),this.timers.delete(e.timer),e.outgoing&&(this.counters.dialsAccepted+=1),this.counters.linksOpened+=1,e.offerSentAt&&We(this.signallingSamples,I()-e.offerSentAt);let i=this.#lt({pubkey:e.pubkey,pc:e.pc,channel:r,maxSegmentBytes:this.options.maxSegmentBytes,onRequest:(a,l,c)=>this.#st(a,l,c),onHaveChange:(a,l)=>{for(let c of[...this.haveWaiters])c(l);this.#k()},onScheduleChange:()=>{for(let a of[...this.haveWaiters])a();for(let a of[...this.peerLeaseWaiters])a();this.#k()},onUploadCancelled:(a,l)=>{this.counters.uploadsCancelled+=1,this.counters.uploadCancelledBytes+=l,this.uploadTokens=Math.min(this.options.maxUploadBytesPerSecond*2,this.uploadTokens+l),this.uploadPacer?.recheck()},onClose:a=>{this.uploadPacer?.cancel(a),this.peerLeases.delete(a);for(let l of[...this.peerLeaseWaiters])l();e.pc.removeEventListener("datachannel",s),this.#de(e.pc,"link-close",a.closeReason),this.peerSelection.forget(a),this.links.get(a.pubkey)===a&&(this.links.delete(a.pubkey),this.discovery.forget(a.pubkey),this.counters.linksClosed+=1,this.#n("reannounce",()=>this.#Be()))}});this.links.set(e.pubkey,i),this.#qe(e.pubkey),this.#k(),this.firstLinkAtMs===null&&(this.firstLinkAtMs=Date.now()-this.startedAt),i.sendContribution(this.#p(),this.rendition);for(let a of this.renditions.keys())a!==this.rendition&&i.sendContribution(this.#p(),a);if(this.#p()){i.sendHave([...this.held.keys()]);for(let a of this.originFetches.keys())i.sendFetching(a,2e3)}let o=await xl(e.pc);this.pairTypes[o]=(this.pairTypes[o]||0)+1;for(let a of[...this.haveWaiters])a()}};var Nh=Object.freeze({version:"0.4.4",sourceCommit:"c8120c5bf8c117e334a37a072b3bd6f3de46cc3a"});export{Ti as KIND_SEGMENT_COMMITMENT,Oi as commitmentContent,xt as commitmentPieceSize,kl as createHlsSwarm,vr as finalizeEvent,Yt as generateSecretKey,Jt as matchFilter,Nh as relayswarmBuild,Ot as segmentMediaContext,Zt as verifyEvent}; /*! Bundled license information: @noble/hashes/utils.js: diff --git a/site/vendor/relayswarm-core.NOTICE.txt b/site/vendor/relayswarm-core.NOTICE.txt index a229406..04769a1 100644 --- a/site/vendor/relayswarm-core.NOTICE.txt +++ b/site/vendor/relayswarm-core.NOTICE.txt @@ -1,5 +1,5 @@ RelaySwarm Rust/WebAssembly core -https://github.com/forgesworn/relayswarm/tree/d4a1235b035b4244ea73b55b1da0d4f88f64c376 +https://github.com/forgesworn/relayswarm/tree/c8120c5bf8c117e334a37a072b3bd6f3de46cc3a MIT License diff --git a/site/vendor/relayswarm-transfer-worker.js b/site/vendor/relayswarm-transfer-worker.js index 1eae19e..05b6ccc 100644 --- a/site/vendor/relayswarm-transfer-worker.js +++ b/site/vendor/relayswarm-transfer-worker.js @@ -1,2 +1,2 @@ -/*! RelaySwarm 0.4.4 transfer worker; public source d4a1235b035b4244ea73b55b1da0d4f88f64c376. See media-peer-demo.NOTICE.txt. */ +/*! RelaySwarm 0.4.4 transfer worker; public source c8120c5bf8c117e334a37a072b3bd6f3de46cc3a. See media-peer-demo.NOTICE.txt. */ var B=new TextEncoder,j=new TextDecoder;function k(e,t,r){let i=t.byteLength,o=e.rs_alloc(i);try{return new Uint8Array(e.memory.buffer,o,i).set(t),r(o,i)}finally{e.rs_free(o,i)}}var R=(e,t)=>new Uint8Array(e.memory.buffer,e.rs_result_ptr(),t);function I(e,{size:t,sha256:r,pieces:i,deadline:o,maxHolders:l,originReserveMs:c,peerOnly:n=!1},s,d){if(s()||!E.every(f=>typeof e[f]=="function")||typeof n!="boolean")return null;if(n)try{if(typeof e.rs_xfer_capabilities!="function"||!(e.rs_xfer_capabilities()&2))return null}catch{return null}try{let f=k(e,B.encode(JSON.stringify({sha256:r,pieces:i,...n?{peerOnly:!0}:{}})),(a,h)=>e.rs_xfer_new(t,o,l,c,a,h));return f?new _(e,f,s,d,n):null}catch(f){return d(f),null}}async function z(e,{onFailure:t}={}){if(!(e instanceof WebAssembly.Module))throw new TypeError("A compiled core module is required.");let{exports:r}=await WebAssembly.instantiate(e,{});for(let l of["memory","rs_alloc","rs_free","rs_result_ptr",...E])if(!r[l])throw new Error(`Core transfer module lacks ${l}.`);let i=!1,o=l=>{if(!i){i=!0;try{t?.(l)}catch{}}};return Object.freeze({get retired(){return i},retire(){i=!0},transfer(l){return I(r,l,()=>i,o)}})}var E=["rs_xfer_new","rs_xfer_call","rs_xfer_free"],b={start:0,delivered:1,failed:2,tick:3,state:4,progress:5},_=class{#r;#e;#n;#i;#s;constructor(t,r,i,o,l=!1){this.#r=t,this.#e=r,this.#n=i,this.#i=o,this.#s=l}start(t,{peers:r,origin:i,sharedFirstByteMs:o=null,sharedRate:l=null,probePeers:c=[]}){let n=!1;try{n=typeof this.#r.rs_xfer_capabilities=="function"&&!!(this.#r.rs_xfer_capabilities()&1)}catch{}let s=new Set(c),d=n?r:r.filter(([f])=>!s.has(f));return this.#t(b.start,t,-1,0,0,B.encode(JSON.stringify({peers:d,origin:this.#s?null:i,sharedFirstByteMs:o,sharedRate:l,...n?{probePeers:c}:{}})))}delivered(t,r,i,o){return this.#t(b.delivered,t,r,i.start,i.end,o)}failed(t,r){return this.#t(b.failed,t,r,0,0,A)}tick(t){return this.#t(b.tick,t,-1,0,0,A)}progress(t,r,i){return this.#t(b.progress,t,r,i,0,A)}free(){if(this.#e===null)return;let t=this.#e;if(this.#e=null,!this.#n())try{this.#r.rs_xfer_free(t)}catch(r){this.#i(r)}}#t(t,r,i,o,l,c){if(this.#e===null||this.#n())return null;let n=this.#r;try{let s=k(n,c,(u,y)=>n.rs_xfer_call(this.#e,t,Math.floor(r),i==="origin"?-1:i,o,l,u,y));if(s<4)throw new Error(`Core transfer refused operation ${t}.`);let d=R(n,s),f=new DataView(d.buffer,d.byteOffset,s).getUint32(0,!0),a=JSON.parse(j.decode(d.subarray(4,4+f))),h=s>4+f?d.slice(4+f):null;return{commands:a.c.map(u=>u.p?{...u,range:{start:u.p[0],end:u.p[1]}}:u),next:a.next,late:a.late,finished:a.finished,verified:a.verified??null,bytes:h}}catch(s){return this.#i(s),null}}},A=new Uint8Array(0);var N=Object.freeze({maxTransfers:2,maxSegmentBytes:16777216,maxActiveBytes:33554432,maxPending:32,maxPendingBytes:33554432,initTimeoutMs:5e3,operationTimeoutMs:5e3}),C=Object.freeze({maxTransfers:4,maxSegmentBytes:32*1048576,maxActiveBytes:64*1048576,maxPending:128,maxPendingBytes:64*1048576,initTimeoutMs:3e4,operationTimeoutMs:3e4}),L=e=>typeof e=="string"&&e.length===64&&/^[a-f0-9]{64}$/.test(e),p=e=>Number.isSafeInteger(e)&&e>=0,x=e=>Number.isFinite(e)&&e>=0&&e<=Number.MAX_SAFE_INTEGER,v=e=>e===null||x(e);var m=class extends Error{constructor(t){super(`Core transfer worker: ${t}.`),this.name="CoreTransferWorkerError",this.code=t}};function O(e={}){let t={};for(let[r,i]of Object.entries(N)){let o=e[r]??i;if(!Number.isSafeInteger(o)||o<1||o>C[r])throw new m("invalid-limits");t[r]=o}return Object.freeze(t)}function S(e,t){if(!e||!Array.isArray(e.pieces)||e.pieces.length<1||e.pieces.length>256)throw new m("invalid-transfer");let r=e&&{size:e.size,sha256:e.sha256,pieces:e.pieces?.slice(),deadline:e.deadline,maxHolders:e.maxHolders,originReserveMs:e.originReserveMs,...e.peerOnly===!0?{peerOnly:!0}:{}};if(!r||!p(r.size)||r.size<1||r.size>t.maxSegmentBytes||!L(r.sha256)||!Array.isArray(r.pieces)||r.pieces.length<1||r.pieces.length>256||!r.pieces.every(L)||!x(r.deadline)||!p(r.maxHolders)||r.maxHolders<1||r.maxHolders>32||!x(r.originReserveMs)||e.peerOnly!==void 0&&typeof e.peerOnly!="boolean")throw new m("invalid-transfer");return r}function P(e,t,r,i=!1){let[o,l,c]=t;if(!x(o))throw new m("invalid-operation");if(e==="start"){let n=l;if(!n||!Array.isArray(n.peers)||n.peers.length>32||!n.peers.every(s=>Array.isArray(s)&&s.length===3&&p(s[0])&&v(s[1])&&v(s[2]))||(i?n.origin!=null:!Array.isArray(n.origin)||n.origin.length!==2||!n.origin.every(v))||!v(n.sharedFirstByteMs??null)||!v(n.sharedRate??null)||!Array.isArray(n.probePeers??[])||(n.probePeers?.length??0)>32||!(n.probePeers??[]).every(p))throw new m("invalid-operation");return[o,{peers:n.peers.map(s=>[...s]),origin:i?null:[...n.origin],sharedFirstByteMs:n.sharedFirstByteMs??null,sharedRate:n.sharedRate??null,probePeers:[...n.probePeers??[]]}]}if(e==="tick")return[o];if(l!=="origin"&&!p(l))throw new m("invalid-operation");if(i&&l==="origin")throw new m("invalid-operation");if(e==="failed")return[o,l];if(e==="progress"&&p(c)&&c<=r)return[o,l,c];if(e==="delivered"&&c&&p(c.start)&&p(c.end)&&c.starte({v:1,id:d,ok:!0,result:f},f?.bytes?[f.bytes.buffer]:[]),s=(d,f,a=!1)=>{a&&(i=!0),e({v:1,id:d,ok:!1,error:f,fatal:a})};return async function({data:f}){if(!f||f.v!==1||!Number.isSafeInteger(f.id)||f.id<1||typeof f.op!="string")return;let{id:a,op:h,handle:g,input:u}=f;if(i)return s(a,"worker-failed",!0);try{if(h==="init")return t||o||!(u?.module instanceof WebAssembly.Module)?s(a,"invalid-init",!0):(o=!0,r=O(u.limits),t=await z(u.module,{onFailure:()=>{i=!0}}),i?s(a,"core-failed",!0):n(a,!0));if(!t)return s(a,"not-ready");if(!Number.isSafeInteger(g)||g<1)return s(a,"invalid-handle");if(h==="new"){let w=S(u,r);if(c.has(g)||c.size>=r.maxTransfers||l+w.size>r.maxActiveBytes)return s(a,"transfer-limit");let M=t.transfer(w);return M?(c.set(g,{transfer:M,size:w.size,peerOnly:w.peerOnly===!0}),l+=w.size,n(a,!0)):s(a,i||t.retired?"core-failed":"invalid-transfer",i||t.retired)}let y=c.get(g);if(h==="free")return y&&(y.transfer.free(),c.delete(g),l-=y.size),i||t.retired?s(a,"core-failed",!0):n(a,!0);if(!y)return s(a,"unknown-transfer");if(!["start","delivered","failed","progress","tick"].includes(h)||!Array.isArray(u))return s(a,"invalid-operation");let W=P(h,u,r.maxSegmentBytes,y.peerOnly),T=y.transfer[h](...W);if(!T||i||t.retired)return s(a,"core-failed",!0);n(a,T)}catch(y){s(a,y?.code??"worker-failed",!y?.code)}}}if(typeof DedicatedWorkerGlobalScope<"u"&&globalThis instanceof DedicatedWorkerGlobalScope){let e=F((t,r)=>globalThis.postMessage(t,r));globalThis.addEventListener("message",e)}export{F as createCoreTransferWorkerRuntime}; diff --git a/test/media-playback-report.test.mjs b/test/media-playback-report.test.mjs index 982c081..bbc5a92 100644 --- a/test/media-playback-report.test.mjs +++ b/test/media-playback-report.test.mjs @@ -117,6 +117,59 @@ test('unreadable peer diagnostics remain unknown without discarding or aliasing assert.equal(p.report.snapshot().samples[0].peerAttemptDiagnostics.peerNoFit, 2); }); +test('peer flow observations preserve measured models without awarding playback or sharing mutable state', () => { + const p = fixture(); + const model = { decision: 'cooldown-blocked', availableMs: 1800, pieceSize: 65536, + firstByteMs: 7, rateBytesPerSecond: null, probeAgeMs: 500, usefulAgeMs: null }; + const flow = { verifiedShortBatches: 2, verifiedShortBytes: 786432, + lastVerifiedShortBatch: { bytes: 393216, spanMs: 350 }, + modelEvaluations: { fit: 2, 'useful-unknown': 3, refresh: 1, 'cooldown-blocked': 1, 'known-slow': 0 }, + lastModel: model, noModelTransfers: 1, lastNoModel: { candidateCount: 1, model } }; + p.report.record({ position: 4, peerBytes: 0, peerAttemptDiagnostics: { core: { multiHolder: { peerFlow: flow } } } }); + flow.lastVerifiedShortBatch.bytes = 1; model.firstByteMs = 100; flow.modelEvaluations.fit = 99; + const row = p.report.snapshot().samples[0], d = row.peerFlowDiagnostics; + assert.equal(row.position, 4); assert.equal(row.peerBytes, 0); + assert.equal(d.verifiedShortBatches, 2); assert.equal(d.verifiedShortBytes, 786432); + assert.deepEqual(d.lastVerifiedShortBatch, { bytes: 393216, spanMs: 350 }); + assert.deepEqual(d.modelEvaluations, { fit: 2, 'useful-unknown': 3, refresh: 1, 'cooldown-blocked': 1, 'known-slow': 0 }); + assert.equal(d.lastModel.firstByteMs, 7); assert.equal(d.lastModel.rateBytesPerSecond, null); + assert.equal(d.lastNoModel.model.firstByteMs, 7); assert.equal(d.lastNoModel.candidateCount, 1); + d.lastNoModel.model.firstByteMs = 999; + assert.equal(p.report.snapshot().samples[0].peerFlowDiagnostics.lastNoModel.model.firstByteMs, 7); +}); + +test('peer flow reporting rejects unknown types and private payloads while retaining unreadable fields as unknown', () => { + const p = fixture(); p.report.record({}); + p.at(1200); p.report.record({ peerAttemptDiagnostics: { core: { multiHolder: { peerFlow: [] } } } }); + assert.equal(p.report.snapshot().samples[0].peerFlowDiagnostics, null); + assert.equal(p.report.snapshot().samples[1].peerFlowDiagnostics, null); + let serialized = false, privateRead = false; + const secret = { toJSON() { serialized = true; return 'credential-secret'; } }; + const model = { decision: 'https://private.invalid/credential-secret', availableMs: Infinity, pieceSize: '65536', + firstByteMs: -1, rateBytesPerSecond: secret, probeAgeMs: NaN, usefulAgeMs: 0, owner: secret }; + Object.defineProperty(model, 'privateKey', { get() { privateRead = true; throw new Error('private'); } }); + const flow = { verifiedShortBatches: 0, verifiedShortBytes: Number.MAX_SAFE_INTEGER + 1, + lastVerifiedShortBatch: secret, modelEvaluations: { fit: 0, 'useful-unknown': '0', refresh: -1, + 'cooldown-blocked': secret, 'known-slow': 0.5, credential: secret }, lastModel: model, + noModelTransfers: 0, lastNoModel: { candidateCount: false, model, pubkey: secret }, records: [secret], toJSON: secret.toJSON }; + Object.defineProperty(flow, 'lastVerifiedShortBatch', { get() { throw new Error('unreadable'); } }); + p.at(2400); assert.equal(p.report.record({ position: 8, peerAttemptDiagnostics: { core: { multiHolder: { peerFlow: flow } } } }), true); + const row = p.report.snapshot().samples.at(-1), d = row.peerFlowDiagnostics; + assert.equal(row.position, 8); assert.equal(d.verifiedShortBatches, 0); assert.equal(d.verifiedShortBytes, null); + assert.equal(d.lastVerifiedShortBatch, null); assert.equal(d.lastModel.decision, null); + for (const name of ['availableMs', 'pieceSize', 'firstByteMs', 'rateBytesPerSecond', 'probeAgeMs']) assert.equal(d.lastModel[name], null); + assert.equal(d.lastModel.usefulAgeMs, 0); assert.equal(d.lastNoModel.candidateCount, null); + assert.deepEqual(d.modelEvaluations, { fit: 0, 'useful-unknown': null, refresh: null, 'cooldown-blocked': null, 'known-slow': null }); + const invalidCore = []; + Object.defineProperty(invalidCore, 'multiHolder', { get() { privateRead = true; return secret; } }); + p.at(3600); p.report.record({ peerAttemptDiagnostics: { core: invalidCore } }); + assert.equal(p.report.snapshot().samples.at(-1).peerFlowDiagnostics, null); + const output = JSON.stringify(p.report.snapshot()); + assert.equal(serialized, false); assert.equal(privateRead, false); + assert.doesNotMatch(output, /secret|private\.invalid|privateKey|"(?:owner|pubkey|records|credential)"\s*:/); + assert.equal(p.report.snapshot().maxSamples, 240); +}); + test('skipped ticks do not invoke native observation work', () => { const p = fixture(); let reads = 0; const observe = () => { reads++; return { position: reads }; };