From 03764cf38e64c5f2885f5cec10b663883be2be48 Mon Sep 17 00:00:00 2001 From: TheCryptoDonkey <147930957+TheCryptoDonkey@users.noreply.github.com> Date: Tue, 27 Oct 2026 13:53:10 +0000 Subject: [PATCH 1/3] fix: preserve source availability through loader cleanup --- docs/media-showcase.md | 12 +++++++++--- scripts/build-media-peer-demo.mjs | 2 +- site/live-media.html | 2 +- site/llms.txt | 2 +- site/media-lab.html | 2 +- site/media-lab.mjs | 4 ++-- site/media-listener-session.mjs | 2 +- site/media-public-swarm.mjs | 4 ++-- site/template.html | 2 +- site/vendor/media-peer-demo.NOTICE.txt | 2 +- site/vendor/media-peer-demo.build.json | 10 +++++----- site/vendor/media-peer-demo.js | 8 ++++---- site/vendor/relayswarm-core.NOTICE.txt | 2 +- site/vendor/relayswarm-transfer-worker.js | 2 +- 14 files changed, 31 insertions(+), 25 deletions(-) diff --git a/docs/media-showcase.md b/docs/media-showcase.md index aa27f27..eef368d 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 `a27c1804455699e9d8c8e5d48928680a3b6ba458` -([source change](https://github.com/forgesworn/relayswarm/commit/a27c1804455699e9d8c8e5d48928680a3b6ba458)). +The player pins RelaySwarm source `167b1c971c94456983da28d32dede00cd4c3123b` +([source change](https://github.com/forgesworn/relayswarm/commit/167b1c971c94456983da28d32dede00cd4c3123b)). 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 permits one extra contiguous startup fragment when the @@ -26,8 +26,14 @@ bounded to four objects within the existing 24 MiB reservation; steady warm-ahead keeps its three-object limit. The eight-second deadline, authority checks and explicit refusal for insufficient capacity remain. The Rust/WASM binary is unchanged. +When an owned whole-source response finishes and its key is already known, +eligible retained bytes are announced with HAVE before its FETCH claim is +withdrawn, including synchronous hls.js disposal. Unknown keys do not delay +playback for another hash; cache limits, serving permission and receiver +verification remain unchanged. No new peer-wait policy is enabled. Earlier playback measurements below retain their captured revisions; this -update does not establish a bandwidth saving or a new physical-phone result. +update does not establish a bandwidth saving, smoother playback or a new +physical-phone result. The [27 October public pair attempt](evidence/public-pair-startup-red-20261027.json) did not complete its planned observation: the first viewer presented 4K after diff --git a/scripts/build-media-peer-demo.mjs b/scripts/build-media-peer-demo.mjs index a531daa..6b8eb02 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 = 'a27c1804455699e9d8c8e5d48928680a3b6ba458'; +const SOURCE = '167b1c971c94456983da28d32dede00cd4c3123b'; 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 20a8a30..bcfc68a 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 626568d..6ff89cf 100644 --- a/site/llms.txt +++ b/site/llms.txt @@ -7,7 +7,7 @@ - [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 e910147 (package version 0.4.4), including bounded rolling startup planning from verified future-load timing, with sustainable peer waits, range-sized WASM upload inputs and cached schema-3 mixed admission despite late whole-object estimates. 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 167b1c971c94456983da28d32dede00cd4c3123b (package version 0.4.4), retaining bounded rolling startup planning, sustainable peer waits and range-sized WASM uploads. 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. 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. - [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 8c9053f..0c7c52e 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 2c75ed5..25c3554 100644 --- a/site/media-lab.mjs +++ b/site/media-lab.mjs @@ -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=20261027-bounded-startup-window'), import('./media-public-swarm.mjs?v=20261027-local-turn-lease'), + import('./media-listener-session.mjs?v=20261027-origin-fetch-ownership'), import('./media-public-swarm.mjs?v=20261027-origin-fetch-ownership'), ]); 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=20261027-local-turn-lease'); + const { createPublicSwarm, prepareRecordedSource, createRecordedLive } = await import('./media-public-swarm.mjs?v=20261027-origin-fetch-ownership'); 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 df9395b..744a89f 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=20261027-bounded-startup-window'; +import { finalizeEvent, generateSecretKey, verifyEvent } from './vendor/media-peer-demo.js?v=20261027-origin-fetch-ownership'; export const LISTENER_SESSION_KIND = 30378; export const LISTENER_TELEMETRY_KIND = 20378; diff --git a/site/media-public-swarm.mjs b/site/media-public-swarm.mjs index f4f7c3a..89c89e4 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=20261027-bounded-startup-window'; + generateSecretKey, relayswarmBuild } from './vendor/media-peer-demo.js?v=20261027-origin-fetch-ownership'; 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=20261027-bounded-startup-window', import.meta.url), + transferWorkerUrl: new URL('./vendor/relayswarm-transfer-worker.js?v=20261027-origin-fetch-ownership', import.meta.url), zeroBudgetPeerRace: true, lateHaveRace: true, sustainablePeerWait: true, warmAhead: false, startupBufferTarget: needsStartupBuffer ? () => { diff --git a/site/template.html b/site/template.html index 00ab97c..be79220 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 fb5cbf1..b8417cb 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/a27c1804455699e9d8c8e5d48928680a3b6ba458 +https://github.com/forgesworn/relayswarm/tree/167b1c971c94456983da28d32dede00cd4c3123b MIT License diff --git a/site/vendor/media-peer-demo.build.json b/site/vendor/media-peer-demo.build.json index 8582b07..5a976b3 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": "a27c1804455699e9d8c8e5d48928680a3b6ba458", + "sourceCommit": "167b1c971c94456983da28d32dede00cd4c3123b", "version": "0.4.4", - "sourceArchiveSha256": "0e6506436ebb68c1cc2815b598c0dddf1aa4f1b51f41f80f1a7e5e5d45ea7409", + "sourceArchiveSha256": "f3cd9621efe6e6bc9dde9df078738fd5821f0a9030baba1b85351330cb8ff94d", "packageLockSha256": "18a91b8d697ebcab1d259d4de876167dcbd4d47fc3c82196d179c4c490adca4a", "bundle": "media-peer-demo.js", - "bundleSha256": "8cec4d288b80a15d2034206c95c9c17b6a51a52502b4a58e9d9fd6121df6ce73", - "bundleBytes": 260358, + "bundleSha256": "a3b50af45602e5455f35faa60884becd18354d21f0fa57f46c84c8043e347654", + "bundleBytes": 260708, "transferWorker": { "file": "relayswarm-transfer-worker.js", "bytes": 7074, - "sha256": "8775d3aadfb066d0e80546246f71b909b4152d0d2b3797e3c65071c0da3c51e7", + "sha256": "7391dad0c29956401ac9aba155e04cfa12ddc9317c366c2a09e9831d6d046f9d", "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 4ee721c..f40d710 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 a27c1804455699e9d8c8e5d48928680a3b6ba458. See media-peer-demo.NOTICE.txt. */ -function Zr(r,e){try{let t=a=>{if(!r)return null;let l=typeof r.getResponseHeader=="function"?r.getResponseHeader(a):r.headers?.get?.(a);return typeof l=="string"?l:null},n=t("Date"),s=typeof n=="string"&&/\sGMT$/u.test(n.trim())?Date.parse(n):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 Xr(r){return{samples:r.length,offsetSeconds:r.length?Math.round(Math.max(...r)/1e3):null}}function Dt(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function He(r,e=""){if(!Number.isSafeInteger(r)||r<0){let t=e&&`"${e}" `;throw new Error(`${t}expected integer >= 0, got ${r}`)}}function se(r,e,t=""){let n=Dt(r),s=r?.length,i=e!==void 0;if(!n||i&&s!==e){let o=t&&`"${t}" `,a=i?` of length ${e}`:"",l=n?`length=${s}`:`type=${typeof r}`;throw new Error(o+"expected Uint8Array"+a+", got "+l)}return r}function pt(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash must wrapped by utils.createHasher");He(r.outputLen),He(r.blockLen)}function Et(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function Qr(r,e){se(r,void 0,"digestInto() output");let t=e.outputLen;if(r.length='+t)}function Ge(...r){for(let e=0;e>>e}var es=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",to=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function De(r){if(se(r),es)return r.toHex();let e="";for(let t=0;t=$e._0&&r<=$e._9)return r-$e._0;if(r>=$e.A&&r<=$e.F)return r-($e.A-10);if(r>=$e.a&&r<=$e.f)return r-($e.a-10)}function Oe(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(es)return Uint8Array.fromHex(r);let e=r.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(t);for(let s=0,i=0;sr(i).update(s).digest(),n=r(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=s=>r(s),Object.assign(t,e),Object.freeze(t)}function Ye(r=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(r))}var ns=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function rs(r,e,t){return r&e^~r&t}function ss(r,e,t){return r&e^r&t^e&t}var an=class{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,s){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=s,this.buffer=new Uint8Array(e),this.view=on(this.buffer)}update(e){Et(this),se(e);let{view:t,buffer:n,blockLen:s}=this,i=e.length;for(let o=0;os-o&&(this.process(n,0),o=0);for(let u=o;uh.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u>>3,m=ze(g,17)^ze(g,19)^g>>>10;tt[u]=m+tt[u-7]+f+tt[u-16]|0}let{A:n,B:s,C:i,D:o,E:a,F:l,G:c,H:h}=this;for(let u=0;u<64;u++){let p=ze(a,6)^ze(a,11)^ze(a,25),g=h+p+rs(a,l,c)+no[u]+tt[u]|0,m=(ze(n,2)^ze(n,13)^ze(n,22))+ss(n,s,i)|0;h=c,c=l,l=a,a=o+g|0,o=i,i=s,s=n,n=g+m|0}n=n+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,h=h+this.H|0,this.set(n,s,i,o,a,l,c,h)}roundClean(){Ge(tt)}destroy(){this.set(0,0,0,0,0,0,0,0),Ge(this.buffer)}},$n=class extends Vn{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=ts(()=>new $n,ns(1));var Yn=BigInt(0),Gn=BigInt(1);function Ut(r,e=""){if(typeof r!="boolean"){let t=e&&`"${e}" `;throw new Error(t+"expected boolean, got type="+typeof r)}return r}function is(r){if(typeof r=="bigint"){if(!ln(r))throw new Error("positive bigint expected, got "+r)}else He(r);return r}function zt(r){let e=is(r).toString(16);return e.length&1?"0"+e:e}function os(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?Yn:BigInt("0x"+r)}function nt(r){return os(De(r))}function Zn(r){return os(De(ro(se(r)).reverse()))}function cn(r,e){He(e),r=is(r);let t=Oe(r.toString(16).padStart(e*2,"0"));if(t.length!==e)throw new Error("number too large");return t}function Xn(r,e){return cn(r,e).reverse()}function ro(r){return Uint8Array.from(r)}function as(r){return Uint8Array.from(r,(e,t)=>{let n=e.charCodeAt(0);if(e.length!==1||n>127)throw new Error(`string contains non-ASCII character "${r[t]}" with code ${n} at position ${t}`);return n})}var ln=r=>typeof r=="bigint"&&Yn<=r;function so(r,e,t){return ln(r)&&ln(e)&&ln(t)&&e<=r&&rYn;r>>=Gn,e+=1);return e}var qt=r=>(Gn<new Uint8Array(y),s=Uint8Array.of(),i=Uint8Array.of(0),o=Uint8Array.of(1),a=1e3,l=n(r),c=n(r),h=0,u=()=>{l.fill(1),c.fill(0),h=0},p=(...y)=>t(c,Se(l,...y)),g=(y=s)=>{c=p(i,y),l=p(),y.length!==0&&(c=p(o,y),l=p())},f=()=>{if(h++>=a)throw new Error("drbg: tried max amount of iterations");let y=0,w=[];for(;y{u(),g(y);let b;for(;!(b=w(f()));)g();return u(),b}}function Ft(r,e={},t={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function n(i,o,a){let l=r[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])=>n(a,l,o));s(e,!1),s(t,!0)}function Qn(r){let e=new WeakMap;return(t,...n)=>{let s=e.get(t);if(s!==void 0)return s;let i=r(t,...n);return e.set(t,i),i}}var Le=BigInt(0),Re=BigInt(1),gt=BigInt(2),ds=BigInt(3),fs=BigInt(4),ps=BigInt(5),io=BigInt(7),gs=BigInt(8),oo=BigInt(9),ms=BigInt(16);function qe(r,e){let t=r%e;return t>=Le?t:e+t}function Ne(r,e,t){let n=r;for(;e-- >Le;)n*=n,n%=t;return n}function hs(r,e){if(r===Le)throw new Error("invert: expected non-zero number");if(e<=Le)throw new Error("invert: expected positive modulus, got "+e);let t=qe(r,e),n=e,s=Le,i=Re,o=Re,a=Le;for(;t!==Le;){let c=n/t,h=n%t,u=s-o*c,p=i-a*c;n=t,t=h,s=o,i=a,o=u,a=p}if(n!==Re)throw new Error("invert: does not exist");return qe(s,e)}function tr(r,e,t){if(!r.eql(r.sqr(e),t))throw new Error("Cannot find square root")}function ys(r,e){let t=(r.ORDER+Re)/fs,n=r.pow(e,t);return tr(r,n,e),n}function ao(r,e){let t=(r.ORDER-ps)/gs,n=r.mul(e,gt),s=r.pow(n,t),i=r.mul(e,s),o=r.mul(r.mul(i,gt),s),a=r.mul(i,r.sub(o,r.ONE));return tr(r,a,e),a}function lo(r){let e=At(r),t=bs(r),n=t(e,e.neg(e.ONE)),s=t(e,n),i=t(e,e.neg(n)),o=(r+io)/ms;return(a,l)=>{let c=a.pow(l,o),h=a.mul(c,n),u=a.mul(c,s),p=a.mul(c,i),g=a.eql(a.sqr(h),l),f=a.eql(a.sqr(u),l);c=a.cmov(c,h,g),h=a.cmov(p,u,f);let m=a.eql(a.sqr(h),l),y=a.cmov(c,h,m);return tr(a,y,l),y}}function bs(r){if(r1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return ys;let i=s.pow(n,e),o=(e+Re)/gt;return function(l,c){if(l.is0(c))return c;if(us(l,c)!==1)throw new Error("Cannot find square root");let h=t,u=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===h)throw new Error("Cannot find square root");let y=Re<(n[s]="function",n),e);return Ft(r,t),r}function uo(r,e,t){if(tLe;)t&Re&&(n=r.mul(n,s)),s=r.sqr(s),t>>=Re;return n}function hn(r,e,t=!1){let n=new Array(e.length).fill(t?r.ZERO:void 0),s=e.reduce((o,a,l)=>r.is0(a)?o:(n[l]=o,r.mul(o,a)),r.ONE),i=r.inv(s);return e.reduceRight((o,a,l)=>r.is0(a)?o:(n[l]=r.mul(o,n[l]),r.mul(o,a)),i),n}function us(r,e){let t=(r.ORDER-Re)/gt,n=r.pow(e,t),s=r.eql(n,r.ONE),i=r.eql(n,r.ZERO),o=r.eql(n,r.neg(r.ONE));if(!s&&!i&&!o)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function fo(r,e){e!==void 0&&He(e);let t=e!==void 0?e:r.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}var er=class{ORDER;BITS;BYTES;isLE;ZERO=Le;ONE=Re;_lengths;_sqrt;_mod;constructor(e,t={}){if(e<=Le)throw new Error("invalid field: expected ORDER > 0, got "+e);let n;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(n=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}=fo(e,n);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 qe(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return Le<=e&&es)throw new Error("Field.fromBytes: expected "+n+" 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?Zn(e):nt(e);if(a&&(l=qe(l,o)),!t&&!this.isValid(l))throw new Error("invalid field element: outside of range 0..ORDER");return l}invertBatch(e){return hn(this,e)}cmov(e,t,n){return n?t:e}};function At(r,e={}){return new er(r,e)}function ws(r){if(typeof r!="bigint")throw new Error("field order must be bigint");let e=r.toString(2).length;return Math.ceil(e/8)}function rr(r){let e=ws(r);return e+Math.ceil(e/2)}function un(r,e,t=!1){se(r);let n=r.length,s=ws(e),i=rr(e);if(n<16||n1024)throw new Error("expected "+i+"-1024 bytes of input, got "+n);let o=t?Zn(r):nt(r),a=qe(o,e-Re)+Re;return t?Xn(a,s):cn(a,s)}var kt=BigInt(0),mt=BigInt(1);function jt(r,e){let t=e.negate();return r?t:e}function ar(r,e){let t=hn(r.Fp,e.map(n=>n.Z));return e.map((n,s)=>r.fromAffine(n.toAffine(t[s])))}function Es(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function sr(r,e){Es(r,e);let t=Math.ceil(e/r)+1,n=2**(r-1),s=2**r,i=qt(r),o=BigInt(r);return{windows:t,windowSize:n,mask:i,maxNumber:s,shiftBy:o}}function vs(r,e,t){let{windowSize:n,mask:s,maxNumber:i,shiftBy:o}=t,a=Number(r&s),l=r>>o;a>n&&(a-=i,l+=mt);let c=e*n,h=c+Math.abs(a)-1,u=a===0,p=a<0,g=e%2!==0;return{nextN:l,offset:h,isZero:u,isNeg:p,isNegF:g,offsetF:c}}var ir=new WeakMap,As=new WeakMap;function or(r){return As.get(r)||1}function xs(r){if(r!==kt)throw new Error("invalid wNAF")}var dn=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,n=this.ZERO){let s=e;for(;t>kt;)t&mt&&(n=n.add(s)),s=s.double(),t>>=mt;return n}precomputeWindow(e,t){let{windows:n,windowSize:s}=sr(t,this.bits),i=[],o=e,a=o;for(let l=0;lkt||n>kt;)t&mt&&(i=i.add(s)),n&mt&&(o=o.add(s)),s=s.double(),t>>=mt,n>>=mt;return{p1:i,p2:o}}function Ss(r,e,t){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return nr(e),e}else return At(r,{isLE:t})}function Ms(r,e,t={},n){if(n===void 0&&(n=r==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${r} CURVE object`);for(let l of["p","n","h"]){let c=e[l];if(!(typeof c=="bigint"&&c>kt))throw new Error(`CURVE.${l} must be positive bigint`)}let s=Ss(e.p,t.Fp,n),i=Ss(e.n,t.Fn,n),a=["Gx","Gy","a",r==="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 fn(r,e){return function(n){let s=r(n);return{secretKey:s,publicKey:e(s)}}}var pn=class{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,t){if(pt(e),se(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 n=this.blockLen,s=new Uint8Array(n);s.set(t.length>n?e.create().update(t).digest():t);for(let i=0;inew pn(r,e).update(t).digest();rt.create=(r,e)=>new pn(r,e);var Bs=(r,e)=>(r+(r>=0?e:-e)/Rs)/e;function po(r,e,t){let[[n,s],[i,o]]=e,a=Bs(o*r,t),l=Bs(-s*r,t),c=r-a*n-l*i,h=-a*s-l*o,u=c=g||h=g)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:u,k1:c,k2neg:p,k2:h}}function cr(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function lr(r,e){let t={};for(let n of Object.keys(e))t[n]=r[n]===void 0?e[n]:r[n];return Ut(t.lowS,"lowS"),Ut(t.prehash,"prehash"),t.format!==void 0&&cr(t.format),t}var hr=class extends Error{constructor(e=""){super(e)}},st={Err:hr,_tlv:{encode:(r,e)=>{let{Err:t}=st;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");let n=e.length/2,s=zt(n);if(s.length/2&128)throw new t("tlv.encode: long form length too big");let i=n>127?zt(s.length/2|128):"";return zt(r)+i+s+e},decode(r,e){let{Err:t}=st,n=0;if(r<0||r>256)throw new t("tlv.encode: wrong tag");if(e.length<2||e[n++]!==r)throw new t("tlv.decode: wrong tlv");let s=e[n++],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(n,n+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 h of c)o=o<<8|h;if(n+=l,o<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+o);if(a.length!==o)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+o)}}},_int:{encode(r){let{Err:e}=st;if(r{let{X:A,Y:v,Z:B}=d;if(n.eql(B,n.ONE))return{x:A,y:v};let O=d.is0();x==null&&(x=O?n.ONE:n.inv(B));let P=n.mul(A,x),T=n.mul(v,x),D=n.mul(B,x);if(O)return{x:n.ZERO,y:n.ZERO};if(!n.eql(D,n.ONE))throw new Error("invZ was invalid");return{x:P,y:T}}),C=Qn(d=>{if(d.is0()){if(e.allowInfinityPoint&&!n.is0(d.Y))return;throw new Error("bad point: ZERO")}let{x,y:A}=d.toAffine();if(!n.isValid(x)||!n.isValid(A))throw new Error("bad point: x or y not field elements");if(!y(x,A))throw new Error("bad point: equation left != right");if(!d.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function U(d,x,A,v,B){return A=new _(n.mul(A.X,d),A.Y,A.Z),x=jt(v,x),A=jt(B,A),x.add(A)}class _{static BASE=new _(i.Gx,i.Gy,n.ONE);static ZERO=new _(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=s;X;Y;Z;constructor(x,A,v){this.X=M("x",x),this.Y=M("y",A,!0),this.Z=M("z",v),Object.freeze(this)}static CURVE(){return i}static fromAffine(x){let{x:A,y:v}=x||{};if(!x||!n.isValid(A)||!n.isValid(v))throw new Error("invalid affine point");if(x instanceof _)throw new Error("projective point not allowed");return n.is0(A)&&n.is0(v)?_.ZERO:new _(A,v,n.ONE)}static fromBytes(x){let A=_.fromAffine(f(se(x,void 0,"point")));return A.assertValidity(),A}static fromHex(x){return _.fromBytes(Oe(x))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(x=8,A=!0){return N.createCache(this,x),A||this.multiply(gn),this}assertValidity(){C(this)}hasEvenY(){let{y:x}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(x)}equals(x){R(x);let{X:A,Y:v,Z:B}=this,{X:O,Y:P,Z:T}=x,D=n.eql(n.mul(A,T),n.mul(O,B)),H=n.eql(n.mul(v,T),n.mul(P,B));return D&&H}negate(){return new _(this.X,n.neg(this.Y),this.Z)}double(){let{a:x,b:A}=i,v=n.mul(A,gn),{X:B,Y:O,Z:P}=this,T=n.ZERO,D=n.ZERO,H=n.ZERO,F=n.mul(B,B),ee=n.mul(O,O),j=n.mul(P,P),V=n.mul(B,O);return V=n.add(V,V),H=n.mul(B,P),H=n.add(H,H),T=n.mul(x,H),D=n.mul(v,j),D=n.add(T,D),T=n.sub(ee,D),D=n.add(ee,D),D=n.mul(T,D),T=n.mul(V,T),H=n.mul(v,H),j=n.mul(x,j),V=n.sub(F,j),V=n.mul(x,V),V=n.add(V,H),H=n.add(F,F),F=n.add(H,F),F=n.add(F,j),F=n.mul(F,V),D=n.add(D,F),j=n.mul(O,P),j=n.add(j,j),F=n.mul(j,V),T=n.sub(T,F),H=n.mul(j,ee),H=n.add(H,H),H=n.add(H,H),new _(T,D,H)}add(x){R(x);let{X:A,Y:v,Z:B}=this,{X:O,Y:P,Z:T}=x,D=n.ZERO,H=n.ZERO,F=n.ZERO,ee=i.a,j=n.mul(i.b,gn),V=n.mul(A,O),ne=n.mul(v,P),ae=n.mul(B,T),ge=n.add(A,v),re=n.add(O,P);ge=n.mul(ge,re),re=n.add(V,ne),ge=n.sub(ge,re),re=n.add(A,B);let pe=n.add(O,T);return re=n.mul(re,pe),pe=n.add(V,ae),re=n.sub(re,pe),pe=n.add(v,B),D=n.add(P,T),pe=n.mul(pe,D),D=n.add(ne,ae),pe=n.sub(pe,D),F=n.mul(ee,re),D=n.mul(j,ae),F=n.add(D,F),D=n.sub(ne,F),F=n.add(ne,F),H=n.mul(D,F),ne=n.add(V,V),ne=n.add(ne,V),ae=n.mul(ee,ae),re=n.mul(j,re),ne=n.add(ne,ae),ae=n.sub(V,ae),ae=n.mul(ee,ae),re=n.add(re,ae),V=n.mul(ne,re),H=n.add(H,V),V=n.mul(pe,re),D=n.mul(ge,D),D=n.sub(D,V),V=n.mul(ge,ne),F=n.mul(pe,F),F=n.add(F,V),new _(D,H,F)}subtract(x){return this.add(x.negate())}is0(){return this.equals(_.ZERO)}multiply(x){let{endo:A}=e;if(!s.isValidNot0(x))throw new Error("invalid scalar: out of range");let v,B,O=P=>N.cached(this,P,T=>ar(_,T));if(A){let{k1neg:P,k1:T,k2neg:D,k2:H}=Z(x),{p:F,f:ee}=O(T),{p:j,f:V}=O(H);B=ee.add(V),v=U(A.beta,F,j,P,D)}else{let{p:P,f:T}=O(x);v=P,B=T}return ar(_,[v,B])[0]}multiplyUnsafe(x){let{endo:A}=e,v=this;if(!s.isValid(x))throw new Error("invalid scalar: out of range");if(x===Xe||v.is0())return _.ZERO;if(x===Mt)return v;if(N.hasCache(this))return this.multiply(x);if(A){let{k1neg:B,k1:O,k2neg:P,k2:T}=Z(x),{p1:D,p2:H}=ks(_,v,O,T);return U(A.beta,D,H,B,P)}else return N.unsafe(v,x)}toAffine(x){return k(this,x)}isTorsionFree(){let{isTorsionFree:x}=e;return o===Mt?!0:x?x(_,this):N.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:x}=e;return o===Mt?this:x?x(_,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(x=!0){return Ut(x,"isCompressed"),this.assertValidity(),g(_,this,x)}toHex(x=!0){return De(this.toBytes(x))}toString(){return``}}let z=s.BITS,N=new dn(_,e.endo?Math.ceil(z/2):z);return _.BASE.precompute(8),_}function Ls(r){return Uint8Array.of(r?2:3)}function _s(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function mo(r,e={}){let{Fn:t}=r,n=e.randomBytes||Ye,s=Object.assign(_s(r.Fp,t),{seed:rr(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:y}=s;try{let w=g.length;return f===!0&&w!==m||f===!1&&w!==y?!1:!!r.fromBytes(g)}catch{return!1}}function a(g=n(s.seed)){return un(se(g,s.seed,"seed"),t.ORDER)}function l(g,f=!0){return r.BASE.multiply(t.fromBytes(g)).toBytes(f)}function c(g){let{secretKey:f,publicKey:m,publicKeyUncompressed:y}=s;if(!Dt(g)||"_lengths"in t&&t._lengths||f===m)return;let w=se(g,void 0,"key").length;return w===m||w===y}function h(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 y=t.fromBytes(g);return r.fromBytes(f).multiply(y).toBytes(m)}let u={isValidSecretKey:i,isValidPublicKey:o,randomSecretKey:a},p=fn(a,l);return Object.freeze({getPublicKey:l,getSharedSecret:h,keygen:p,Point:r,utils:u,lengths:s})}function Os(r,e,t={}){pt(e),Ft(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),t=Object.assign({},t);let n=t.randomBytes||Ye,s=t.hmac||((A,v)=>rt(e,A,v)),{Fp:i,Fn:o}=r,{ORDER:a,BITS:l}=o,{keygen:c,getPublicKey:h,getSharedSecret:u,utils:p,lengths:g}=mo(r,t),f={prehash:!0,lowS:typeof t.lowS=="boolean"?t.lowS:!0,format:"compact",extraEntropy:!1},m=a*Rs>Mt;return A>v}function w(A,v){if(!o.isValidNot0(v))throw new Error(`invalid signature ${A}: out of range 1..Point.Fn.ORDER`);return v}function b(){if(m)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function M(A,v){cr(v);let B=g.signature,O=v==="compact"?B:v==="recovered"?B+1:void 0;return se(A,O)}class R{r;s;recovery;constructor(v,B,O){if(this.r=w("r",v),this.s=w("s",B),O!=null){if(b(),![0,1,2,3].includes(O))throw new Error("invalid recovery id");this.recovery=O}Object.freeze(this)}static fromBytes(v,B=f.format){M(v,B);let O;if(B==="der"){let{r:H,s:F}=st.toSig(se(v));return new R(H,F)}B==="recovered"&&(O=v[0],B="compact",v=v.subarray(1));let P=g.signature/2,T=v.subarray(0,P),D=v.subarray(P,P*2);return new R(o.fromBytes(T),o.fromBytes(D),O)}static fromHex(v,B){return this.fromBytes(Oe(v),B)}assertRecovery(){let{recovery:v}=this;if(v==null)throw new Error("invalid recovery id: must be present");return v}addRecoveryBit(v){return new R(this.r,this.s,v)}recoverPublicKey(v){let{r:B,s:O}=this,P=this.assertRecovery(),T=P===2||P===3?B+a:B;if(!i.isValid(T))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let D=i.toBytes(T),H=r.fromBytes(Se(Ls((P&1)===0),D)),F=o.inv(T),ee=k(se(v,void 0,"msgHash")),j=o.create(-ee*F),V=o.create(O*F),ne=r.BASE.multiplyUnsafe(j).add(H.multiplyUnsafe(V));if(ne.is0())throw new Error("invalid recovery: point at infinify");return ne.assertValidity(),ne}hasHighS(){return y(this.s)}toBytes(v=f.format){if(cr(v),v==="der")return Oe(st.hexFromSig(this));let{r:B,s:O}=this,P=o.toBytes(B),T=o.toBytes(O);return v==="recovered"?(b(),Se(Uint8Array.of(this.assertRecovery()),P,T)):Se(P,T)}toHex(v){return De(this.toBytes(v))}}let Z=t.bits2int||function(v){if(v.length>8192)throw new Error("input is too large");let B=nt(v),O=v.length*8-l;return O>0?B>>BigInt(O):B},k=t.bits2int_modN||function(v){return o.create(Z(v))},C=qt(l);function U(A){return ls("num < 2^"+l,A,Xe,C),o.toBytes(A)}function _(A,v){return se(A,void 0,"message"),v?se(e(A),void 0,"prehashed message"):A}function z(A,v,B){let{lowS:O,prehash:P,extraEntropy:T}=lr(B,f);A=_(A,P);let D=k(A),H=o.fromBytes(v);if(!o.isValidNot0(H))throw new Error("invalid private key");let F=[U(H),U(D)];if(T!=null&&T!==!1){let ne=T===!0?n(g.secretKey):T;F.push(se(ne,void 0,"extraEntropy"))}let ee=Se(...F),j=D;function V(ne){let ae=Z(ne);if(!o.isValidNot0(ae))return;let ge=o.inv(ae),re=r.BASE.multiply(ae).toAffine(),pe=o.create(re.x);if(pe===Xe)return;let Q=o.create(ge*o.create(j+pe*H));if(Q===Xe)return;let me=(re.x===pe?0:2)|Number(re.y&Mt),et=Q;return O&&y(Q)&&(et=o.neg(Q),me^=1),new R(pe,et,m?void 0:me)}return{seed:ee,k2sig:V}}function N(A,v,B={}){let{seed:O,k2sig:P}=z(A,v,B);return cs(e.outputLen,o.BYTES,s)(O,P).toBytes(B.format)}function d(A,v,B,O={}){let{lowS:P,prehash:T,format:D}=lr(O,f);if(B=se(B,void 0,"publicKey"),v=_(v,T),!Dt(A)){let H=A instanceof R?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+H)}M(A,D);try{let H=R.fromBytes(A,D),F=r.fromBytes(B);if(P&&H.hasHighS())return!1;let{r:ee,s:j}=H,V=k(v),ne=o.inv(j),ae=o.create(V*ne),ge=o.create(ee*ne),re=r.BASE.multiplyUnsafe(ae).add(F.multiplyUnsafe(ge));return re.is0()?!1:o.create(re.x)===ee}catch{return!1}}function x(A,v,B={}){let{prehash:O}=lr(B,f);return v=_(v,O),R.fromBytes(A,"recovered").recoverPublicKey(v).toBytes()}return Object.freeze({keygen:c,getPublicKey:h,getSharedSecret:u,utils:p,lengths:g,Point:r,sign:N,verify:d,recoverPublicKey:x,Signature:R,hash:e})}var bn={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},yo={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},bo=BigInt(0),ur=BigInt(2);function wo(r){let e=bn.p,t=BigInt(3),n=BigInt(6),s=BigInt(11),i=BigInt(22),o=BigInt(23),a=BigInt(44),l=BigInt(88),c=r*r*r%e,h=c*c*r%e,u=Ne(h,t,e)*h%e,p=Ne(u,t,e)*h%e,g=Ne(p,ur,e)*c%e,f=Ne(g,s,e)*g%e,m=Ne(f,i,e)*f%e,y=Ne(m,a,e)*m%e,w=Ne(y,l,e)*y%e,b=Ne(w,a,e)*m%e,M=Ne(b,t,e)*h%e,R=Ne(M,o,e)*f%e,Z=Ne(R,n,e)*c%e,k=Ne(Z,ur,e);if(!mn.eql(mn.sqr(k),r))throw new Error("Cannot find square root");return k}var mn=At(bn.p,{sqrt:wo}),yt=Ts(bn,{Fp:mn,endo:yo}),Ns=Os(yt,Fe),Is={};function yn(r,...e){let t=Is[r];if(t===void 0){let n=Fe(as(r));t=Se(n,n),Is[r]=t}return Fe(Se(t,...e))}var fr=r=>r.toBytes(!0).slice(1),pr=r=>r%ur===bo;function dr(r){let{Fn:e,BASE:t}=yt,n=e.fromBytes(r),s=t.multiply(n);return{scalar:pr(s.y)?n:e.neg(n),bytes:fr(s)}}function Ps(r){let e=mn;if(!e.isValidNot0(r))throw new Error("invalid x: Fail if x \u2265 p");let t=e.create(r*r),n=e.create(t*r+BigInt(7)),s=e.sqrt(n);pr(s)||(s=e.neg(s));let i=yt.fromAffine({x:r,y:s});return i.assertValidity(),i}var Wt=nt;function Hs(...r){return yt.Fn.create(Wt(yn("BIP0340/challenge",...r)))}function Cs(r){return dr(r).bytes}function vo(r,e,t=Ye(32)){let{Fn:n}=yt,s=se(r,void 0,"message"),{bytes:i,scalar:o}=dr(e),a=se(t,32,"auxRand"),l=n.toBytes(o^Wt(yn("BIP0340/aux",a))),c=yn("BIP0340/nonce",l,i,s),{bytes:h,scalar:u}=dr(c),p=Hs(h,i,s),g=new Uint8Array(64);if(g.set(h,0),g.set(n.toBytes(n.create(u+p*o)),32),!Ds(g,s,i))throw new Error("sign: Invalid signature produced");return g}function Ds(r,e,t){let{Fp:n,Fn:s,BASE:i}=yt,o=se(r,64,"signature"),a=se(e,void 0,"message"),l=se(t,32,"publicKey");try{let c=Ps(Wt(l)),h=Wt(o.subarray(0,32));if(!n.isValidNot0(h))return!1;let u=Wt(o.subarray(32,64));if(!s.isValidNot0(u))return!1;let p=Hs(s.toBytes(h),fr(c),a),g=i.multiplyUnsafe(u).add(c.multiplyUnsafe(s.neg(p))),{x:f,y:m}=g.toAffine();return!(g.is0()||!pr(m)||f!==h)}catch{return!1}}var Bt=(()=>{let t=(n=Ye(48))=>un(n,bn.n);return{keygen:fn(t,Cs),getPublicKey:Cs,sign:vo,verify:Ds,Point:yt,utils:{randomSecretKey:t,taggedHash:yn,lift_x:Ps,pointToBytes:fr},lengths:{secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:64,seed:48}}})();var tc=new TextDecoder("utf-8"),xo=new TextEncoder;function So(r){for(let e=0;e<64;e++){let t=r.charCodeAt(e);if(isNaN(t)||t<48||t>102||t>57&&t<97)return!1}return!0}var Rt=Symbol("verified"),Eo=r=>r instanceof Object;function Ao(r){if(!Eo(r)||typeof r.kind!="number"||typeof r.content!="string"||typeof r.created_at!="number"||typeof r.pubkey!="string"||!So(r.pubkey)||!Array.isArray(r.tags))return!1;for(let e=0;e{function t(n,...s){if(Ee(n,void 0,"key"),!To)throw new Error("Non little-endian hardware is not yet supported");if(r.nonceLength!==void 0){let h=s[0];Ee(h,r.varSizeNonce?void 0:r.nonceLength,"nonce")}let i=r.tagLength;i&&s[1]!==void 0&&Ee(s[1],void 0,"AAD");let o=e(n,...s),a=(h,u)=>{if(u!==void 0){if(h!==2)throw new Error("cipher output not supported");Ee(u,void 0,"output")}},l=!1;return{encrypt(h,u){if(l)throw new Error("cannot encrypt() twice with same key + nonce");return l=!0,Ee(h),a(o.encrypt.length,u),o.encrypt(h,u)},decrypt(h,u){if(Ee(h),i&&h.lengthUint8Array.from(r.split(""),e=>e.charCodeAt(0)),_o=Ws("expand 16-byte k"),Oo=Ws("expand 32-byte k"),Io=Je(_o),Co=Je(Oo);function G(r,e){return r<>>32-e}function br(r){return r.byteOffset%4===0}var An=64,No=16,Ks=2**32-1,js=Uint32Array.of();function Po(r,e,t,n,s,i,o,a){let l=s.length,c=new Uint8Array(An),h=Je(c),u=br(s)&&br(i),p=u?Je(s):js,g=u?Je(i):js;for(let f=0;f=Ks)throw new Error("arx: counter overflow");let m=Math.min(An,l-f);if(u&&m===An){let y=f/4;if(f%4!==0)throw new Error("arx: invalid block position");for(let w=0,b;w{Ee(a,void 0,"key"),Ee(l,void 0,"nonce"),Ee(c,void 0,"data");let p=c.length;if(h===void 0&&(h=new Uint8Array(p)),Ee(h,void 0,"output"),Sn(u),u<0||u>=Ks)throw new Error("arx: counter overflow");if(h.length>>13|n<<3)&8191,this.r[2]=(n>>>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 h=0;h<8;h++)this.pad[h]=ke(e,16+2*h)}process(e,t,n=!1){let s=n?0:2048,{h:i,r:o}=this,a=o[0],l=o[1],c=o[2],h=o[3],u=o[4],p=o[5],g=o[6],f=o[7],m=o[8],y=o[9],w=ke(e,t+0),b=ke(e,t+2),M=ke(e,t+4),R=ke(e,t+6),Z=ke(e,t+8),k=ke(e,t+10),C=ke(e,t+12),U=ke(e,t+14),_=i[0]+(w&8191),z=i[1]+((w>>>13|b<<3)&8191),N=i[2]+((b>>>10|M<<6)&8191),d=i[3]+((M>>>7|R<<9)&8191),x=i[4]+((R>>>4|Z<<12)&8191),A=i[5]+(Z>>>1&8191),v=i[6]+((Z>>>14|k<<2)&8191),B=i[7]+((k>>>11|C<<5)&8191),O=i[8]+((C>>>8|U<<8)&8191),P=i[9]+(U>>>5|s),T=0,D=T+_*a+z*(5*y)+N*(5*m)+d*(5*f)+x*(5*g);T=D>>>13,D&=8191,D+=A*(5*p)+v*(5*u)+B*(5*h)+O*(5*c)+P*(5*l),T+=D>>>13,D&=8191;let H=T+_*l+z*a+N*(5*y)+d*(5*m)+x*(5*f);T=H>>>13,H&=8191,H+=A*(5*g)+v*(5*p)+B*(5*u)+O*(5*h)+P*(5*c),T+=H>>>13,H&=8191;let F=T+_*c+z*l+N*a+d*(5*y)+x*(5*m);T=F>>>13,F&=8191,F+=A*(5*f)+v*(5*g)+B*(5*p)+O*(5*u)+P*(5*h),T+=F>>>13,F&=8191;let ee=T+_*h+z*c+N*l+d*a+x*(5*y);T=ee>>>13,ee&=8191,ee+=A*(5*m)+v*(5*f)+B*(5*g)+O*(5*p)+P*(5*u),T+=ee>>>13,ee&=8191;let j=T+_*u+z*h+N*c+d*l+x*a;T=j>>>13,j&=8191,j+=A*(5*y)+v*(5*m)+B*(5*f)+O*(5*g)+P*(5*p),T+=j>>>13,j&=8191;let V=T+_*p+z*u+N*h+d*c+x*l;T=V>>>13,V&=8191,V+=A*a+v*(5*y)+B*(5*m)+O*(5*f)+P*(5*g),T+=V>>>13,V&=8191;let ne=T+_*g+z*p+N*u+d*h+x*c;T=ne>>>13,ne&=8191,ne+=A*l+v*a+B*(5*y)+O*(5*m)+P*(5*f),T+=ne>>>13,ne&=8191;let ae=T+_*f+z*g+N*p+d*u+x*h;T=ae>>>13,ae&=8191,ae+=A*c+v*l+B*a+O*(5*y)+P*(5*m),T+=ae>>>13,ae&=8191;let ge=T+_*m+z*f+N*g+d*p+x*u;T=ge>>>13,ge&=8191,ge+=A*h+v*c+B*l+O*a+P*(5*y),T+=ge>>>13,ge&=8191;let re=T+_*y+z*m+N*f+d*g+x*p;T=re>>>13,re&=8191,re+=A*u+v*h+B*c+O*l+P*a,T+=re>>>13,re&=8191,T=(T<<2)+T|0,T=T+D|0,D=T&8191,T=T>>>13,H+=T,i[0]=D,i[1]=H,i[2]=F,i[3]=ee,i[4]=j,i[5]=V,i[6]=ne,i[7]=ae,i[8]=ge,i[9]=re}finalize(){let{h:e,pad:t}=this,n=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,n[0]=e[0]+5,s=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=e[a]+s,s=n[a]>>>13,n[a]&=8191;n[9]-=8192;let i=(s^1)-1;for(let a=0;a<10;a++)n[a]&=i;i=~i;for(let a=0;a<10;a++)e[a]=e[a]&i|n[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(n)}update(e){gr(this),Ee(e),e=Tt(e);let{buffer:t,blockLen:n}=this,s=e.length;for(let i=0;i>>0,e[i++]=n[o]>>>8;return e}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}};function Ho(r){let e=(n,s)=>r(s).update(n).digest(),t=r(new Uint8Array(32));return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=n=>r(n),e}var Vs=Ho(r=>new vr(r));function Ys(r,e,t,n,s,i=20){let o=r[0],a=r[1],l=r[2],c=r[3],h=e[0],u=e[1],p=e[2],g=e[3],f=e[4],m=e[5],y=e[6],w=e[7],b=s,M=t[0],R=t[1],Z=t[2],k=o,C=a,U=l,_=c,z=h,N=u,d=p,x=g,A=f,v=m,B=y,O=w,P=b,T=M,D=R,H=Z;for(let ee=0;ee{r.update(e);let t=e.length%16;t&&r.update(zo.subarray(t))},qo=new Uint8Array(32);function Gs(r,e,t,n,s){s!==void 0&&Ee(s,void 0,"AAD");let i=r(e,t,qo),o=Fs(n.length,s?s.length:0,!0),a=Vs.create(i);s&&$s(a,s),$s(a,n),a.update(o);let l=a.digest();return Qe(i,o),l}var Zs=r=>(e,t,n)=>({encrypt(i,o){let a=i.length;o=yr(a+16,o,!1),o.set(i);let l=o.subarray(0,-16);r(e,t,l,l,1);let c=Gs(r,e,t,l,n);return o.set(c,a),Qe(c),o},decrypt(i,o){o=yr(i.length-16,o,!1);let a=i.subarray(0,-16),l=i.subarray(-16),c=Gs(r,e,t,a,n);if(!En(l,c))throw new Error("invalid tag");return o.set(i.subarray(0,-16)),r(e,t,o,o,1),Qe(c),o}}),wc=mr({blockSize:64,nonceLength:12,tagLength:16},Zs(kn)),vc=mr({blockSize:64,nonceLength:24,tagLength:16},Zs(Uo));function Js(r,e,t){return pt(r),t===void 0&&(t=new Uint8Array(r.outputLen)),rt(r,t,e)}var xr=Uint8Array.of(0),Xs=Uint8Array.of();function Qs(r,e,t,n=32){pt(r),He(n,"length");let s=r.outputLen;if(n>255*s)throw new Error("Length must be <= 255*HashLen");let i=Math.ceil(n/s);t===void 0?t=Xs:se(t,void 0,"info");let o=new Uint8Array(i*s),a=rt.create(r,e),l=a._cloneInto(),c=new Uint8Array(a.outputLen);for(let h=0;htypeof t=="string"):e.every(t=>Number.isSafeInteger(t)):!1}function Gt(r,e){if(typeof e!="string")throw new Error(`${r}: string expected`);return!0}function Ar(r){if(!Number.isSafeInteger(r))throw new Error(`invalid integer: ${r}`)}function Er(r){if(!Array.isArray(r))throw new Error("array expected")}function Mn(r,e){if(!ni(!0,e))throw new Error(`${r}: array of strings expected`)}function jo(r,e){if(!ni(!1,e))throw new Error(`${r}: array of numbers expected`)}function Wo(...r){let e=i=>i,t=(i,o)=>a=>i(o(a)),n=r.map(i=>i.encode).reduceRight(t,e),s=r.map(i=>i.decode).reduce(t,e);return{encode:n,decode:s}}function Ko(r){let e=typeof r=="string"?r.split(""):r,t=e.length;Mn("alphabet",e);let n=new Map(e.map((s,i)=>[s,i]));return{encode:s=>(Er(s),s.map(i=>{if(!Number.isSafeInteger(i)||i<0||i>=t)throw new Error(`alphabet.encode: digit index outside alphabet "${i}". Allowed: ${r}`);return e[i]})),decode:s=>(Er(s),s.map(i=>{Gt("alphabet.decode",i);let o=n.get(i);if(o===void 0)throw new Error(`Unknown letter: "${i}". Allowed: ${r}`);return o}))}}function Vo(r=""){return Gt("join",r),{encode:e=>(Mn("join.decode",e),e.join(r)),decode:e=>(Gt("join.decode",e),e.split(r))}}function $o(r,e="="){return Ar(r),Gt("padding",e),{encode(t){for(Mn("padding.encode",t);t.length*r%8;)t.push(e);return t},decode(t){Mn("padding.decode",t);let n=t.length;if(n*r%8)throw new Error("padding: invalid, string should have whole number of bytes");for(;n>0&&t[n-1]===e;n--)if((n-1)*r%8===0)throw new Error("padding: invalid, string has too much padding");return t.slice(0,n)}}}var ri=(r,e)=>e===0?r:ri(e,r%e),Bn=(r,e)=>r+(e-ri(r,e)),Sr=(()=>{let r=[];for(let e=0;e<40;e++)r.push(2**e);return r})();function ei(r,e,t,n){if(Er(r),e<=0||e>32)throw new Error(`convertRadix2: wrong from=${e}`);if(t<=0||t>32)throw new Error(`convertRadix2: wrong to=${t}`);if(Bn(e,t)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${t} carryBits=${Bn(e,t)}`);let s=0,i=0,o=Sr[e],a=Sr[t]-1,l=[];for(let c of r){if(Ar(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 h=Sr[i];if(h===void 0)throw new Error("invalid carry");s&=h-1}if(s=s<=e)throw new Error("Excess padding");if(!n&&s>0)throw new Error(`Non-zero padding: ${s}`);return n&&i>0&&l.push(s>>>0),l}function Go(r,e=!1){if(Ar(r),r<=0||r>32)throw new Error("radix2: bits should be in (0..32]");if(Bn(8,r)>32||Bn(r,8)>32)throw new Error("radix2: carry overflow");return{encode:t=>{if(!ti(t))throw new Error("radix2.encode input should be Uint8Array");return ei(Array.from(t),8,r,!e)},decode:t=>(jo("radix2.decode",t),Uint8Array.from(ei(t,r,8,e)))}}var Yo=typeof Uint8Array.from([]).toBase64=="function"&&typeof Uint8Array.fromBase64=="function",Zo=(r,e)=>{Gt("base64",r);let t=e?/^[A-Za-z0-9=_-]+$/:/^[A-Za-z0-9=+/]+$/,n=e?"base64url":"base64";if(r.length>0&&!t.test(r))throw new Error("invalid base64");return Uint8Array.fromBase64(r,{alphabet:n,lastChunkHandling:"strict"})},kr=Yo?{encode(r){return Fo(r),r.toBase64()},decode(r){return Zo(r,!1)}}:Wo(Go(6),Ko("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),$o(6),Vo(""));var Xo=new TextDecoder("utf-8"),si=new TextEncoder,Mr=1,Br=4294967295,Rr=65536;function Jo(r,e){let t=Ns.getSharedSecret(r,Oe("02"+e)).subarray(1,33);return Js(Fe,t,si.encode("nip44-v2"))}function ii(r,e){let t=Qs(Fe,r,e,76);return{chacha_key:t.subarray(0,32),chacha_nonce:t.subarray(32,44),hmac_key:t.subarray(44,76)}}function Tr(r){if(!Number.isSafeInteger(r)||r<1)throw new Error("expected positive integer");if(r<=32)return 32;let e=2**(Math.floor(Math.log2(r-1))+1),t=e<=256?32:e/8;return t*(Math.floor((r-1)/t)+1)}function Qo(r){if(!Number.isSafeInteger(r)||r65535)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,r,!1),e}function ea(r){if(!Number.isSafeInteger(r)||rBr)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,r,!1),e}function oi(r){let e=si.encode(r),t=e.length;if(tBr)throw new Error("invalid plaintext size: must be between 1 and 4294967295 bytes");let n=t>=Rr?Se(new Uint8Array([0,0]),ea(t)):Qo(t),s=new Uint8Array(Tr(t)-t);return Se(n,e,s)}function ai(r){let e=new DataView(r.buffer,r.byteOffset,r.byteLength),t=e.getUint16(0),n,s;if(t===0){if(n=e.getUint32(2),nBr||i.length!==n||r.length!==s+Tr(n))throw new Error("invalid padding");return Xo.decode(i)}function li(r,e,t){if(t.length!==32)throw new Error("AAD associated data must be 32 bytes");let n=Se(t,e);return rt(Fe,r,n)}function ta(r){if(typeof r!="string")throw new Error("payload must be a valid string");let e=r.length;if(e<132)throw new Error("invalid payload length: "+e);if(r[0]==="#")throw new Error("unknown encryption version");let t;try{t=kr.decode(r)}catch(i){throw new Error("invalid base64: "+i.message)}let n=t.length;if(n<99)throw new Error("invalid data length: "+n);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 na(r,e,t=Ye(32)){let{chacha_key:n,chacha_nonce:s,hmac_key:i}=ii(e,t),o=oi(r),a=kn(n,s,o),l=li(i,a,t);return kr.encode(Se(new Uint8Array([2]),t,a,l))}function ra(r,e){let{nonce:t,ciphertext:n,mac:s}=ta(r),{chacha_key:i,chacha_nonce:o,hmac_key:a}=ii(e,t),l=li(a,n,t);if(!En(l,s))throw new Error("invalid MAC");let c=kn(i,o,n);return ai(c)}var Rn={utils:{getConversationKey:Jo,calcPaddedLen:Tr,pad:oi,unpad:ai},encrypt:na,decrypt:ra};function Yt(r,e){if(r.ids&&r.ids.indexOf(e.id)===-1||r.kinds&&r.kinds.indexOf(e.kind)===-1||r.authors&&r.authors.indexOf(e.pubkey)===-1)return!1;for(let t in r)if(t[0]==="#"){let n=t.slice(1),s=r[`#${n}`];if(s&&!e.tags.find(([i,o])=>i===t.slice(1)&&s.indexOf(o)!==-1))return!1}return!(r.since&&e.created_atr.until)}var Tn=3,Ln=24170,Lr=24171,_n="x",Zt=/^[0-9a-f]{64}$/u,sa=/^[a-z0-9](?:[a-z0-9-]{0,31})$/u,ia=1*1024*1024,ci=16*1024,oa=64*1024,hi=8*1024,aa=2*1024,ui=30,la=64,ca=256,di=new TextEncoder;function bt(r){return typeof r=="string"?di.encode(r).byteLength:r instanceof ArrayBuffer||ArrayBuffer.isView(r)?r.byteLength:di.encode(String(r)).byteLength}function ha(r){return Array.from(globalThis.crypto.getRandomValues(new Uint8Array(r)),e=>e.toString(16).padStart(2,"0")).join("")}function yi(r,e){return Array.isArray(r?.tags)?r.tags.filter(t=>Array.isArray(t)&&t.length>=2&&t[0]===e&&typeof t[1]=="string").map(t=>t[1]):[]}var _r=r=>Math.min(Number.MAX_SAFE_INTEGER,r);function fi(r,e){let t=yi(r,e);return t.length===1?t[0]:null}function pi(r){let e=JSON.parse(r);if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Expected a JSON object.");return e}function it(r){return typeof r=="string"&&sa.test(r)}function gi(r){return typeof r=="string"&&r.length>=8&&r.length<=64&&/^[a-zA-Z0-9_-]+$/u.test(r)}function ua(r){let e=new URL(String(r)),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 On=class{constructor(e,{label:t="relay",WebSocketImpl:n=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 n!="function")throw new Error("RelayPool requires a WebSocket implementation.");this.urls=[...new Set(e.map(ua))],this.label=t,this.WebSocketImpl=n,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,n=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){n.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){n.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 n;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,n)=>{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{}n(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,h]of this.subscriptions)i.send(JSON.stringify(["REQ",c,h]));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 n=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)})},n);this.retryTimers.add(s)}#s(e){if(this.closed||bt(e)>ia)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 n=t[2],s=this.subscriptions.get(t[1]);try{s&&!Yt(s,n)&&s.since&&Number.isSafeInteger(n.created_at)&&n.created_at1e4&&this.seen.delete(this.seen.values().next().value);for(let i of this.handlers)i(n)}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=ha(8),n=JSON.stringify(["REQ",t,e]);this.subscriptions.set(t,e);for(let s of this.sockets)s.send(n);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 n of this.sockets)n.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()}},In=class{#r=null;#t=null;#e=new Map;#s=null;constructor({pool:e,swarmId:t,secretKey:n=Vt(),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=n,this.pubkey=Us(n),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,n)=>t-n);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={[`#${_n}`]:[this.swarmId],since:Math.floor(Date.now()/1e3)-2};try{this.#t=this.pool.onRelayOpen?.(t=>{if(!this.started||!this.#r)return;let n=Math.floor(Date.now()/1e3)-this.#r.created_at;if(!Number.isFinite(n)||!Number.isFinite(this.maxEventAgeSeconds)||n<-ui||n>this.maxEventAgeSeconds){this.#r=null;return}t(this.#r)}),this.subscriptionId=this.pool.subscribe({...e,since:Math.floor(Date.now()/1e3)-this.maxEventAgeSeconds,kinds:[Ln]}),this.subscriptionIds.push(this.subscriptionId),this.subscriptionIds.push(this.pool.subscribe({...e,kinds:[Lr],"#p":[this.pubkey]}))}catch(t){for(let n of this.subscriptionIds)this.pool.unsubscribe?.(n);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:n=[],open:s,ticket:i}={}){if(i!==void 0&&!we(i))throw new Error("Invalid presence ticket.");if(!it(e))throw new Error("Invalid presence role.");if(!Array.isArray(t)||t.length>8)throw new Error("Invalid transport capability list.");if(!Array.isArray(n)||n.length>32||n.some(c=>!Zt.test(c)))throw new Error("Invalid object hash list.");let o=t.map(c=>{if(!c||typeof c!="object"||!it(c.type)||!Zt.test(c.publicKey)||c.obj!==void 0&&!mi(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:Tn,role:e,transports:o,have:[...new Set(n)],...s===void 0?{}:{open:!!s},...i===void 0?{}:{ticket:i}});if(bt(a)>ci)throw new Error("Presence payload is too large.");let l=vn({kind:Ln,created_at:Math.floor(Date.now()/1e3),tags:[[_n,this.swarmId]],content:a},this.secretKey);return this.pool.publish(l),this.#r=JSON.parse(JSON.stringify(l)),l}sendSignal(e,{type:t,transport:n,requestId:s,payload:i={}}={}){if(!Zt.test(e))throw new Error("Invalid signal recipient.");if(!it(t)||!it(n)||!gi(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:Tn,type:t,transport:n,requestId:s,payload:i});if(bt(o)>hi)throw new Error("Signal payload is too large.");let a=Rn.encrypt(o,this.#n(e)),l=vn({kind:Lr,created_at:Math.floor(Date.now()/1e3),tags:[[_n,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,n,s){return new Promise((i,o)=>{let a=c=>{let h=!1;try{h=t(c)}catch(u){clearTimeout(l),e.delete(a),o(u);return}h&&(clearTimeout(l),e.delete(a),i(c))},l=setTimeout(()=>{e.delete(a),o(new Error(s))},n);e.add(a)})}#i(e){if(e.pubkey===this.pubkey||e.kind!==Ln&&e.kind!==Lr||!Number.isSafeInteger(e.created_at)||fi(e,_n)!==this.swarmId)return;let t=Math.floor(Date.now()/1e3)-e.created_at;if(t<-ui){this.clock.aheadRejected=_r(this.clock.aheadRejected+1),this.clock.maxAheadSeconds=Math.max(this.clock.maxAheadSeconds,_r(-t));return}if(t>this.maxEventAgeSeconds){this.clock.staleRejected=_r(this.clock.staleRejected+1);return}try{e.kind===Ln?this.#c(e):this.#o(e)}catch{}}#c(e){if(bt(e.content)>ci||yi(e,"p").length!==0)return;let t=pi(e.content);if(t.v!==Tn||!it(t.role)||!Array.isArray(t.transports)||t.transports.length>8||!Array.isArray(t.have)||t.have.length>32||t.have.some(o=>!Zt.test(o)))return;let n=t.transports.map(o=>{if(!o||typeof o!="object"||!it(o.type)||!Zt.test(o.publicKey))throw new Error("Invalid transport capability.");return{type:o.type,publicKey:o.publicKey,...mi(o.obj)?{obj:o.obj}:{}}}),s=typeof t.open=="boolean"?t.open:null,i=we(t.ticket)?t.ticket:null;this.#h(this.presenceHandlers,{from:e.pubkey,event:e,payload:{...t,transports:n,open:s,ticket:i}})}#o(e){if(bt(e.content)>oa||fi(e,"p")!==this.pubkey)return;let t=Rn.decrypt(e.content,this.#n(e.pubkey));if(bt(t)>hi)return;let n=pi(t);n.v!==Tn||!it(n.type)||!it(n.transport)||!gi(n.requestId)||!n.payload||typeof n.payload!="object"||Array.isArray(n.payload)||(this.clock.signalAges.length>=la&&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:n}))}#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=Rn.utils.getConversationKey(this.secretKey,e),this.#e.size>=ca&&this.#e.delete(this.#e.keys().next().value)),this.#e.set(e,t),t}#h(e,t){for(let n of e)Promise.resolve().then(()=>n(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 mi(r){return Number.isSafeInteger(r)&&r>=1&&r<=15}function we(r){return typeof r=="string"&&r.length>0&&bt(r)<=aa}var Or=/^[0-9a-f]{64}$/u,bi="relayswarm-abandon";var wi=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"]),ot=class{static ABANDON_REASON=bi;#r=!1;constructor({pubkey:e,pc:t,channel:n,maxSegmentBytes:s,onRequest:i,onHaveChange:o,onScheduleChange:a,onClose:l,onUploadCancelled:c,maxQueuedRequests:h=4,drainTimeoutMs:u=3e3}){this.pubkey=e,this.pc=t,this.channel=n,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=h,this.drainTimeoutMs=u,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,n.binaryType="arraybuffer",n.bufferedAmountLowThreshold=32768,n.addEventListener("message",p=>{try{this.#e(p.data)}catch{this.close("protocol")}}),n.addEventListener("close",()=>this.close("channel-close")),n.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:n,expectedSize:s,onResult:i,onProgress:o}={}){let a=null;try{a=performance.now()}catch{}let l=!1,c=(h,u=null)=>{if(!l&&(l=!0,typeof i=="function"))try{let p=null;if(Number.isFinite(a))try{p=performance.now()-a}catch{}let g=u?.received??0,f=Number.isFinite(u?.firstByteAt)&&Number.isFinite(a)?u.firstByteAt-a:null;i({outcome:h,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:u?u.size>=0:!1,draining:u?.draining===!0,closeReason:wi.has(this.closeReason)?this.closeReason:null})}catch{}};if(this.closed||this.pending||n?.aborted){let h=Promise.resolve(null);return c(this.closed?"closed":this.pending?"busy":"abort"),h}return new Promise(h=>{let u=this.nextId++,p=b=>{clearTimeout(this.pending.timer),n?.removeEventListener("abort",m),h(b)},g=(b,M=b?"payload":"none",R=!0)=>{if(this.pending?.id!==u)return;let Z=this.pending,k=Z.draining;p(b),this.pending=null,b&&(this.lastDeliveredAt=Date.now()),k&&!this.closed&&this.onScheduleChange?.(this),R&&c(M,Z)},f=b=>{let M=this.pending;if(!M||M.id!==u||M.draining)return;let R=!1;try{R=this.channel.ordered===!0&&this.channel.maxRetransmits===null&&this.channel.maxPacketLifeTime===null&&this.channel.readyState==="open"}catch{}let Z=b!=="request-abort"?"timeout":n?.reason===bi?"abandoned":"abort";if(!R){g(null,Z,!1);try{this.close(b)}finally{c(Z,M)}return}M.draining=!0,M.parts.length=0,p(null),M.timer=setTimeout(()=>{this.pending===M&&M.draining&&this.close(b)},this.drainTimeoutMs),c(Z,M),M.cancelled=this.#t({t:"cancel",id:u})},m=()=>f("request-abort"),y=()=>f("request-timeout"),w=typeof o=="function"?b=>{try{o(b.received,b.size,Number.isFinite(a)?b.firstByteAt-a:null)}catch{}}:null;this.pending={id:u,key:e,expectedSize:s,size:-1,parts:[],chunks:0,received:0,firstByteAt:null,progress:w,draining:!1,cancelled:!1,finish:g,timer:setTimeout(y,Math.max(1,t))},n?.addEventListener("abort",m,{once:!0}),this.#t({t:"want",id:u,k:e})||g(null,"send-error")})}close(e="host"){if(!this.closed){this.closed=!0,this.closeReason=wi.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 n=this.pending;if(!n)return;if(n.size<0)return this.close("protocol");let s=new Uint8Array(e);if(!s.byteLength||s.byteLength>16384||n.chunks>=this.maxChunks)return this.close("protocol");if(n.chunks+=1,n.received+=s.byteLength,this.bytesIn+=s.byteLength,n.received>n.size)return this.close("protocol");if(n.draining)return;if(n.firstByteAt===null)try{n.firstByteAt=performance.now()}catch{}n.parts.push(s),n.progress?.(n);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[n,s]of this.renditions)s2e3)return;for(let[n,s]of this.fetching)s<=Date.now()&&this.fetching.delete(n);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 n of this.uploads)n.id===t.id&&(n.cancelled=!0,n.resume?.());return}case"meta":{let n=this.pending;if(!n)return;if(t.id!==n.id)return n.draining?this.close("protocol"):void 0;if(n.size!==-1)return this.close("protocol");if(n.expectedSize!==void 0&&t.size!==n.expectedSize)return this.close("protocol");if(!Number.isSafeInteger(t.size)||t.size<1||t.size>this.maxSegmentBytes)return this.close("protocol");n.size=t.size;return}case"eof":{let n=this.pending;if(!n)return;if(t.id!==n.id)return n.draining?this.close("protocol"):void 0;if(n.cancelled&&n.size>=0)return n.finish(null);if(n.received!==n.size)return this.close("protocol");if(n.draining)return n.finish(null);let s=new Uint8Array(n.size),i=0;for(let o of n.parts)s.set(o,i),i+=o.byteLength;return n.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"&&Or.test(i)).slice(0,256):[],n=[];if(Array.isArray(e.keys)){this.have.clear();for(let s of t(e.keys))this.have.add(s);n.push(...this.have)}for(let s of t(e.add)){if(this.have.size>=256)break;this.have.add(s),n.push(s)}for(let s of t(e.del))this.have.delete(s);n.length&&this.onHaveChange?.(this,n)}#d(e){if(!Number.isSafeInteger(e.id)||typeof e.k!="string"||!Or.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:n}=e;if(e.cancelled)return this.onUploadCancelled?.(this,0),void this.#t({t:"none",id:n});let s=this.closed?null:await this.onRequest?.(this,t);if(!s)return void this.#t({t:"none",id:n});if(e.cancelled)return this.onUploadCancelled?.(this,s.byteLength),void this.#t({t:"none",id:n});if(!this.#t({t:"meta",id:n,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,n(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 vi(r,e){if(!r.length)return null;let t=[...r].sort((n,s)=>n-s);return t[Math.min(t.length-1,Math.floor(t.length*e))]}var da=r=>vi(r,.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:n=0,totalFlowMs:s=n}={}){Number.isFinite(e)&&e>=0&&(this.recentFirstBytes.push(Math.min(6e4,e)),this.recentFirstBytes.length>16&&this.recentFirstBytes.shift()),t>=32768&&n>=300&&(this.recentRates.push({rate:Math.min(1e6,t/n),flowMs:Math.max(n,s||0)}),this.recentRates.length>16&&this.recentRates.shift(),this.lastObservedAt=Date.now())}firstByteMs(){return da(this.recentFirstBytes)}rate(){let e=this.firstByteMs(),t=e===null?[]:this.recentRates.filter(({flowMs:n})=>n>=e*3);return vi((t.length>=2?t:this.recentRates).map(({rate:n})=>n),.75)}projectMs(e){if(!e)return null;let t=this.firstByteMs(),n=this.rate(),s=[this.minimumMs(e),t!==null&&n?t+e/n:0].filter(Boolean);return s.length?Math.min(...s):null}minimumMs(e){if(!e)return 0;let t=0;for(let{bytes:n,rate:s}of this.recentCompletions)n>=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 n=this.summary(e);if(n.latencyMs===null)return null;let s=t&&n.throughputBytesPerSecond?t*1e3/n.throughputBytesPerSecond:0;return Math.max(n.latencyMs,s)}select(e,t,n,s,i=1/0){let o=[...e].filter(f=>!f.closed&&!f.busy&&!n.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),h=a.length&&(!c.length||this.turn===0&&i>=100);this.turn=(this.turn+1)%4;let u=h?a:c.length?c:l,p=f=>{let m=this.summary(f);return h?m.lastSelected:(this.estimate(f,s)??1e3)*(1+m.failureRate*4)},g=u.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+(n?0:.25),s.consecutiveFailures=n?0:Math.min(32,s.consecutiveFailures+1),n&&(s.latencyMs=i(s.latencyMs,o),s.throughputBytesPerSecond=i(s.throughputBytesPerSecond,Math.min(1e9,n*1e3/o)),this.recentCompletions.push({bytes:n,rate:Math.min(1e6,n/o)}),this.lastObservedAt=Date.now(),this.recentCompletions.length>16&&this.recentCompletions.shift()),this.observations.set(e,s)}};var Xt=/^[0-9a-f]{64}$/u,fa=4,pa=1e4,ga=8,xi=2e4,Lt=class{constructor(e=()=>Date.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 n=this.contexts.get(e);if(!n||n.rendition!==t)n={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,n);else{let s=this.clock();(s=3e4||n.lastDemandAt!==null&&(s=3e4))&&(n.keys=[],n.lastDemandAt=null,n.holders.clear()),n.activityAt=this.clock()}return n}demand(e,t,n){let s=this.context(e,t);if(!s||!Xt.test(n))return;let i=this.live()&&this.window.context===s?this.window.attempt?.key:null;return s.keys=[...new Set([...i?[i]:[],n,...s.keys])].slice(0,2),s.lastDemandAt=this.clock(),s}hint(e,t,n){!Xt.test(e)||!Array.isArray(t)||(this.candidates.delete(e),this.candidates.set(e,{pubkey:e,have:[...new Set(t.filter(s=>typeof s=="string"&&Xt.test(s)))].slice(-8),ticket:we(n)?n: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,n){if(!this.#r(e)||!Xt.test(t)||!Xt.test(n))return!1;let s=e.holders.get(t);return s?s.lastKey===n?!1:(s.misses++,s.lastKey=n,!0):(e.holders.size>=ga&&e.holders.delete(e.holders.keys().next().value),e.holders.set(t,{firstMissAt:this.clock(),misses:1,lastKey:n}),!0)}holderAhead(e,t){this.holderDelivered(e,t)}holderDelivered(e,t){this.#r(e)&&e.holders.delete(t)}stale(e,t){let n=this.#r(e)?e.holders.get(t):null;return!!n&&n.misses>=fa&&this.clock()-n.firstMissAt>=pa}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 n=this.clock();return n=e.activityAt&&t-e.activityAt<3e4&&e.lastDemandAt!==null&&t>=e.lastDemandAt&&t-e.lastDemandAt<3e4}choose(e,t,n){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)||!n&&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(n=>t.have.includes(n)))return!0;return!1}hinted(e,t){for(let n of this.candidates.values()){if(this.clock()=6e4||!t(n))continue;let s=e.keys.find(i=>n.have.includes(i));if(s)return{context:e,candidate:n,key:s}}return null}begin({context:e,candidate:t,key:n}){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:n,dial:null,negotiation:null};return s.attempt=i,this.counters.checks++,i}valid(e){let t=e?.window,n=this.candidates.get(e?.pubkey);return!!(t&&this.live(t)&&t.attempt===e&&this.current(t.context)&&n&&this.clock()>=n.at&&this.clock()-n.at<6e4&&n.ticket===e.ticket&&n.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:xi,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 at(r,e,t){return new Promise((n,s)=>{let i=new AbortController,o=!1,a,l=(h,u,p=!1,g=u)=>{o||(o=!0,clearTimeout(a),e?.removeEventListener("abort",c),p&&i.abort(g),h?n(u):s(u))},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 r(i.signal)}).then(h=>l(!0,h),h=>l(!1,h))})}var Si=24172,ma=24173,ya=24174,Ir=/^[0-9a-f]{64}$/u,ba="relayswarm-segment-v1",wa="relayswarm-segment-v2",va="relayswarm-segment-v3",Ei={1:ba,2:wa,3:va},xa=new TextEncoder,Sa=512,vt=new Map;function Cn(r){let e={id:r.id,pubkey:r.pubkey,created_at:r.created_at,kind:r.kind,tags:r.tags,content:r.content,sig:r.sig},t;try{t=Kt(e)}catch{return!1}if(t!==e.id||typeof e.sig!="string")return!1;let n=`${t}:${e.pubkey}:${e.sig}`;return vt.has(n)?(vt.delete(n),vt.set(n,!0),!0):$t(e)?(vt.size>=Sa&&vt.delete(vt.keys().next().value),vt.set(n,!0),!0):!1}function Nn(r){return xa.encode(JSON.stringify(r)).length<=16*1024}function lt(r,e){let t=r.tags.filter(n=>n[0]===e);return t.length===1&&t[0].length===2?t[0][1]:null}function Cr(r){return typeof r=="string"&&/^\/media\/[a-z0-9_./-]+$/iu.test(r)&&!r.split("/").includes("..")}function xt(r){return Math.ceil(Math.max(65536,Math.ceil(r/64))/16384)*16384}function Ai(r){return r.v===3?3:r.v===2?2:1}function ki(r){let e=Ai(r),t=e>=2;return JSON.stringify({domain:Ei[e],v:e,streamEventId:r.streamEventId,swarmId:r.swarmId,key:r.key,rendition:r.rendition,sequence:r.sequence,discontinuity:r.discontinuity,part:r.part,sha256:r.sha256,size:r.size,expiresAt:r.expiresAt,...t?{playlist:r.playlist,mediaType:r.mediaType,encryption:r.encryption}:{},...e===3?{pieceSize:r.pieceSize,pieces:r.pieces}:{}})}function Ea(r){return JSON.stringify({domain:"relayswarm-commitment-delegation-v1",v:1,streamEventId:r.streamEventId,swarmId:r.swarmId,delegatePubkey:r.delegatePubkey,notBefore:r.notBefore,expiresAt:r.expiresAt,renditions:r.renditions,mediaTypes:r.mediaTypes,allowParts:r.allowParts,maxSegmentBytes:r.maxSegmentBytes})}function Aa(r){return JSON.stringify({domain:"relayswarm-commitment-revocation-v1",v:1,streamEventId:r.streamEventId,swarmId:r.swarmId,delegationId:r.delegationId})}function Pn(r){try{return r.kind===30311&&Nn(r)&&Cn(r)&&typeof lt(r,"d")=="string"&&r.tags.some(e=>e.length===3&&e[0]==="relayswarm"&&e[1]==="redistribute"&&e[2]==="1")}catch{return!1}}function ka(r,{streamEvent:e,swarmId:t,revokedDelegationIds:n=[],delegationRevocations:s=[]},i=Date.now()){try{let o=Math.floor(i/1e3);if(!Pn(e)||!r||!Nn(r)||r.kind!==ma||r.pubkey!==e.pubkey||!Cn(r)||lt(r,"x")!==t||lt(r,"e")!==e.id||!Number.isSafeInteger(r.created_at)||r.created_at>o+30||!Array.isArray(n)||n.length>256||n.includes(r.id)||!Array.isArray(s)||s.length>256)return null;let a=JSON.parse(r.content);if(r.content!==Ea(a)||a.domain!=="relayswarm-commitment-delegation-v1"||a.v!==1||a.streamEventId!==e.id||a.swarmId!==t||!Ir.test(a.delegatePubkey)||!Number.isSafeInteger(a.notBefore)||a.notBeforeo||!Number.isSafeInteger(a.expiresAt)||a.expiresAt<=o||a.expiresAt<=a.notBefore||a.expiresAt>r.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=>!(Cr(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||!Nn(l)||l.kind!==ya||l.pubkey!==e.pubkey||!Number.isSafeInteger(l.created_at)||l.created_ato+30||!Cn(l)||lt(l,"e")!==r.id||lt(l,"x")!==t)continue;let c=JSON.parse(l.content);if(l.content===Aa(c)&&c.domain==="relayswarm-commitment-revocation-v1"&&c.v===1&&c.streamEventId===e.id&&c.swarmId===t&&c.delegationId===r.id)return null}return a}catch{return null}}function _t(r){try{let e=r.frag.baseurl||r.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))||!Cr(t.pathname))return null;let n=r.frag.type??"main";if(!["main","audio"].includes(n))return null;let s=r.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||!Cr(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:n,encryption:i}}catch{return null}}function Mi(r,{streamEvent:e,swarmId:t,key:n,context:s,maxSegmentBytes:i,delegation:o,revokedDelegationIds:a,delegationRevocations:l},c=Date.now()){try{let h=Math.floor(c/1e3);if(!Number.isSafeInteger(i)||i<1||i>16*1024*1024||!Pn(e)||!r||r.kind!==Si||!Nn(r)||!Number.isSafeInteger(r.created_at)||r.created_at>h+30||r.created_at=2;if(r.content!==ki(u)||u.domain!==Ei[p]||![1,2,3].includes(u.v)||u.streamEventId!==e.id||u.swarmId!==t||u.key!==n||u.sequence!==s.frag.sn||u.discontinuity!==(s.frag.cc??0)||u.part!==(s.part?.index??null)||!Number.isSafeInteger(u.sequence)||u.sequence<0||!Number.isSafeInteger(u.discontinuity)||u.discontinuity<0||u.part!==null&&(!Number.isSafeInteger(u.part)||u.part<0)||!Ir.test(u.sha256)||!Number.isSafeInteger(u.size)||u.size<1||u.size>i||!Number.isSafeInteger(u.expiresAt)||u.expiresAt<=h||u.expiresAt>h+300||p===3&&(u.pieceSize!==xt(u.size)||!Array.isArray(u.pieces)||u.pieces.length!==Math.ceil(u.size/u.pieceSize)||u.pieces.some(f=>typeof f!="string"||!Ir.test(f))))return null;if(g){let f=_t(s);if(!f||u.rendition!==f.playlist||u.playlist!==f.playlist||u.mediaType!==f.mediaType||JSON.stringify(u.encryption)!==JSON.stringify(f.encryption))return null}else if(u.rendition!==String(s.frag.level)||s.frag.type&&s.frag.type!=="main"||s.frag.decryptdata?.method&&s.frag.decryptdata.method!=="NONE")return null;if(r.pubkey!==e.pubkey){let f=ka(o,{streamEvent:e,swarmId:t,revokedDelegationIds:a,delegationRevocations:l},c);if(!f||r.pubkey!==f.delegatePubkey||lt(r,"delegation")!==o.id||r.created_atf.expiresAt||!f.renditions.includes(u.rendition)||!f.mediaTypes.includes(g?u.mediaType:"main")||u.part!==null&&!f.allowParts||u.size>f.maxSegmentBytes)return null}return u}catch{return null}}var Bi=new TextEncoder,Ma=new TextDecoder;function Ri(r,e,t){let n=e.byteLength,s=r.rs_alloc(n);try{return new Uint8Array(r.memory.buffer,s,n).set(e),t(s,n)}finally{r.rs_free(s,n)}}var Ba=(r,e)=>new Uint8Array(r.memory.buffer,r.rs_result_ptr(),e);function Ti(r,{size:e,sha256:t,pieces:n,deadline:s,maxHolders:i,originReserveMs:o,peerOnly:a=!1},l,c){if(l()||!Ra.every(h=>typeof r[h]=="function")||typeof a!="boolean")return null;if(a)try{if(typeof r.rs_xfer_capabilities!="function"||!(r.rs_xfer_capabilities()&2))return null}catch{return null}try{let h=Ri(r,Bi.encode(JSON.stringify({sha256:t,pieces:n,...a?{peerOnly:!0}:{}})),(u,p)=>r.rs_xfer_new(e,s,i,o,u,p));return h?new Pr(r,h,l,c,a):null}catch(h){return c(h),null}}var Ra=["rs_xfer_new","rs_xfer_call","rs_xfer_free"],Jt={start:0,delivered:1,failed:2,tick:3,state:4,progress:5},Pr=class{#r;#t;#e;#s;#d;constructor(e,t,n,s,i=!1){this.#r=e,this.#t=t,this.#e=n,this.#s=s,this.#d=i}start(e,{peers:t,origin:n,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(([h])=>!l.has(h));return this.#i(Jt.start,e,-1,0,0,Bi.encode(JSON.stringify({peers:c,origin:this.#d?null:n,sharedFirstByteMs:s,sharedRate:i,...a?{probePeers:o}:{}})))}delivered(e,t,n,s){return this.#i(Jt.delivered,e,t,n.start,n.end,s)}failed(e,t){return this.#i(Jt.failed,e,t,0,0,Nr)}tick(e){return this.#i(Jt.tick,e,-1,0,0,Nr)}progress(e,t,n){return this.#i(Jt.progress,e,t,n,0,Nr)}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,n,s,i,o){if(this.#t===null||this.#e())return null;let a=this.#r;try{let l=Ri(a,o,(f,m)=>a.rs_xfer_call(this.#t,e,Math.floor(t),n==="origin"?-1:n,s,i,f,m));if(l<4)throw new Error(`Core transfer refused operation ${e}.`);let c=Ba(a,l),h=new DataView(c.buffer,c.byteOffset,l).getUint32(0,!0),u=JSON.parse(Ma.decode(c.subarray(4,4+h))),p=l>4+h?c.slice(4+h):null;return{commands:u.c.map(f=>f.p?{...f,range:{start:f.p[0],end:f.p[1]}}:f),next:u.next,late:u.late,finished:u.finished,verified:u.verified??null,bytes:p}}catch(l){return this.#s(l),null}}},Nr=new Uint8Array(0);var Me={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},Ue={sendText:1,sendBinary:2,closed:3,report:4,resolved:5,haveChanged:6,scheduleChanged:7,serveRequest:8,uploadCancelled:9,progress:10,serveRange:11},Ta=128*1024,La=32*1024,_a=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"]),ct=new TextEncoder,Ot=new TextDecoder,Hr=new Uint8Array(0),Dr=()=>{try{return globalThis.performance.now()}catch{return null}},Li=r=>{let e=Math.trunc(Math.max(1,r));return e>=1&&e<=2**31-1?e:1},Hn=class r{get supportsRanges(){return!this.closed}static ABANDON_REASON=ot.ABANDON_REASON;#r;#t;#e=-1;#s=null;#d=null;#i=0;#c=!1;#o=!1;#n=new Map;#h=null;#k=!1;#M=0;constructor({pubkey:e,pc:t,channel:n,maxSegmentBytes:s,onRequest:i,onHaveChange:o,onScheduleChange:a,onClose:l,onUploadCancelled:c,maxQueuedRequests:h=4,drainTimeoutMs:u=3e3},p){this.pubkey=e,this.pc=t,this.channel=n,this.maxSegmentBytes=s,this.onRequest=i,this.onHaveChange=o,this.onScheduleChange=a,this.onClose=l,this.onUploadCancelled=c,this.maxQueuedRequests=h,this.drainTimeoutMs=u,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,h,u,this.#l(),this.openedAt),p.links.add(this),n.binaryType="arraybuffer",n.bufferedAmountLowThreshold=La,n.addEventListener("message",g=>{if(this.closed)return;let{data:f}=g;typeof f=="string"?this.#a(Me.text,{bytes:ct.encode(f)}):this.#a(Me.binary,{bytes:f instanceof ArrayBuffer?new Uint8Array(f):ArrayBuffer.isView(f)?new Uint8Array(f.buffer,f.byteOffset,f.byteLength):Hr})}),n.addEventListener("close",()=>this.close("channel-close")),n.addEventListener("error",()=>this.close("channel-error")),n.addEventListener("bufferedamountlow",()=>{this.closed||this.#a(Me.bufferedLow,{a:this.#B()})}),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(Me.sendHave,{bytes:ct.encode(JSON.stringify([...e]))})}sendHaveChange(e=[],t=[]){this.closed||this.#a(Me.sendHaveChange,{bytes:ct.encode(JSON.stringify({add:[...e],del:[...t]}))})}sendContribution(e,t){this.closed||this.#a(Me.sendContribution,{a:e?1:0,bytes:ct.encode(JSON.stringify(typeof t=="string"?t:null))})}sendFetching(e,t=0){this.closed||this.#a(Me.sendFetching,{a:t,bytes:ct.encode(String(e))})}request(e,t,{signal:n,expectedSize:s,onResult:i,onProgress:o,range:a}={}){let l=Dr(),c=!1,h=(p,g=null)=>{if(!c&&(c=!0,typeof i=="function"))try{let f=null;if(Number.isFinite(l)){let w=Dr();Number.isFinite(w)&&(f=w-l)}let m=g?.receivedBytes??0,y=Number.isFinite(u?.firstByteAt)&&Number.isFinite(l)?u.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(y)&&y>=0?y:null,metadataReceived:g?.metadataReceived===!0,draining:g?.draining===!0,closeReason:_a.has(this.closeReason)?this.closeReason:null})}catch{}},u=null;if(this.closed||this.#c||n?.aborted){let p=Promise.resolve(null);return h(this.closed?"closed":this.#c?"busy":"abort"),p}return new Promise(p=>{let g=()=>{u.id!==null&&!this.closed&&this.#a(Me.abort,{a:u.id,b:n?.reason===r.ABANDON_REASON?1:0})};u={id:null,firstByteAt:null,settled:!1,report:h,onProgress:o,startedAt:l,settle:m=>{u.settled||(u.settled=!0,n?.removeEventListener("abort",g),p(m))}};let f=s===void 0?NaN:Number.isSafeInteger(s)&&s>=0?s:-1;this.#h=u;try{a?this.#a(Me.requestRange,{a:Li(t),b:a.objectSize,bytes:ct.encode(JSON.stringify([String(e),a.start,a.end]))}):this.#a(Me.request,{a:Li(t),b:f,bytes:ct.encode(String(e))})}finally{this.#h=null}if(u.id===null){u.settle(null),h("closed");return}u.settled||n?.addEventListener("abort",g,{once:!0})})}close(e="host"){if(!this.closed){if(this.#t===null)return this.#b("host");this.#a(Me.close,{bytes:ct.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:n=0,bytes:s=Hr,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,n,s);o&&this.#A(o)}#A({header:e,events:t}){let[n,s,i,o,a,l,c,h,u,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=h,this.lastServedAt=u,this.lastDeliveredAt=p,!Number.isNaN(f)&&this.#h&&(this.#h.id=f,this.#n.set(f,this.#h)),n!==this.#e&&this.#w(n),this.closed&&this.announced.clear();let y=++this.#M;for(let w of t)this.#O(w);if(y===this.#M&&this.#t!==null&&(this.#Y(g),m===1&&this.#B()<=Ta))return this.#a(Me.bufferedLow,{a:this.#B()});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 n of t.have)this.have.add(n);this.fetching.clear();for(let[n,s]of t.fetching)this.fetching.set(n,s);this.renditions.clear();for(let[n,s]of t.renditions)this.renditions.set(n,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:n}){let s=i=>new DataView(t.buffer,t.byteOffset,t.byteLength).getFloat64(i*8,!0);switch(e){case Ue.sendText:{if(this.#k)return;let i=Ot.decode(t);try{this.channel.send(i)}catch{this.#k=!0,this.close("send-error")}return}case Ue.sendBinary:{if(this.#k)return;try{this.channel.send(t)}catch{this.#k=!0,this.close("serve-error")}return}case Ue.closed:{this.closeReason=Ot.decode(t),this.#I();try{this.channel.close()}catch{}try{this.pc.close()}catch{}this.onClose?.(this);return}case Ue.report:{let i=JSON.parse(Ot.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 Ue.resolved:{let i=Number.isNaN(n)?this.#h:this.#n.get(n);if(!i)return;i.settle(t);return}case Ue.haveChanged:{let i=JSON.parse(Ot.decode(t));this.onHaveChange?.(this,i);return}case Ue.scheduleChanged:{this.onScheduleChange?.(this);return}case Ue.serveRequest:case Ue.serveRange:{let i,o;if(e===Ue.serveRange){let[a,l,c]=JSON.parse(Ot.decode(t));i=a,o={start:l,end:c}}else i=Ot.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 Ue.uploadCancelled:{this.onUploadCancelled?.(this,s(0));return}case Ue.progress:{let i=s(0),o=s(1);for(let a of this.#n.values())if(!a.settled&&(a.firstByteAt===null&&(a.firstByteAt=Dr()),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}.`)}}#B(){try{return Math.max(0,Number(this.channel.bufferedAmount)||0)}catch{return 0}}#v(e,t){if(this.#t===null)return;let n=this.#B(),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(Me.serve,{a:0,b:n});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(Me.serve,{a:0,b:n}):this.#a(Me.serveRange,{a:i,b:n,bytes:s.subarray(t.start*o,Math.min(i,t.end*o))})}this.#a(Me.serve,{a:s?1:0,b:n,bytes:s??Hr})}#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(Me.tick)},Math.max(0,e-this.#f())))}#I(){this.#s!==null&&globalThis.clearTimeout(this.#s),this.#s=null,this.#d=null}};var Oa=/^[0-9a-f]{64}$/u,oe={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},Ia=6e4,Ca=2e4,Na=new Set([oe.stale,oe.current,oe.valid,oe.live,oe.reserved,oe.suppresses]),Qt=class extends Error{constructor(e){super("Core discovery failed.",{cause:e})}},Dn=class{#r;#t;#e=null;#s=new Map;#d=new Map;#i=new WeakMap;#c=null;#o=null;#n=new WeakMap;#h=new WeakMap;#k=new Map;#M=1;#b=null;#S=null;constructor(e,t,n=()=>Date.now()){this.#r=e,this.#t=t,this.clock=n,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(oe.candidates,[]).map(e=>[e.pubkey,e]))}retire(){this.#e||(this.#S=null,this.#e=new Lt(this.clock),this.#e.counters=this.counters)}#l(e,t){if(this.#e)return t(this.#e);try{return e()}catch(n){if(!(n instanceof Qt))throw n;this.retire();try{this.#t?.(n.cause)}catch{}return t(this.#e)}}#f(e,t){try{let n=this.#r(e,this.clock(),t);if(e===oe.candidates)return n.map(([s,i,o,a])=>({pubkey:s,have:i,ticket:o,at:a}));if(Na.has(e)&&typeof n!="boolean")throw new TypeError(`Core discovery answered operation ${e} with ${typeof n}.`);return n}catch(n){throw new Qt(n)}}#a(e,t){try{let{r:n,s}=this.#r(e,this.clock(),t);return this.#A(s),n}catch(n){throw new Qt(n)}}#A({c:e,w:t,n}){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]=n}#w(e){return e?this.#i.get(e)??null:null}#O(e,t){let s=e===null||typeof e!="object"&&typeof e!="function"?this.#k:this.#h,i=s.get(e);return i===void 0&&t&&s.set(e,i=this.#M++),i}#B(e){let t=this.clock();return this.#S??=this.#f(oe.candidates,[]),this.#S.filter(n=>t>=n.at&&t-n.atn.pubkey)}#v(e){if(!e)return this.#b=null;let[t,n,s,i]=e.candidate,o=this.#d.get(e.context);return this.#b=o?{context:o,candidate:{pubkey:t,have:n,ticket:s,at:i},key:e.key}:null}context(e,t){return e!=="main"&&e!=="audio"?null:this.#l(()=>{let n=this.#a(oe.context,[e,String(t)]);return this.#d.get(n)??null},n=>n.context(e,t))}demand(e,t,n){return this.#l(()=>{if(typeof n!="string"){this.context(e,t);return}if(e!=="main"&&e!=="audio")return;let s=this.#a(oe.demand,[e,String(t),n]);return this.#d.get(s)??void 0},s=>s.demand(e,t,n))}hint(e,t,n){typeof e!="string"||!Oa.test(e)||!Array.isArray(t)||this.#l(()=>{this.#S=null,this.#f(oe.hint,[e,t.filter(s=>typeof s=="string"),we(n)?n:null])},s=>s.hint(e,t,n))}holderMiss(e,t,n){if(!(typeof t!="string"||typeof n!="string"))return this.#l(()=>this.#f(oe.holderMiss,[this.#w(e),t,n]),s=>s.holderMiss(e,t,n))}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 n=this.#w(e),s=this.clock();return n===null||!this.spent(e)||sn.rearm(e,t))}holderAhead(e,t){typeof t=="string"&&this.#l(()=>{this.#f(oe.holderAhead,[this.#w(e),t])},n=>n.holderAhead(e,t))}stale(e,t){return typeof t!="string"?!1:this.#l(()=>this.#f(oe.stale,[this.#w(e),t]),n=>n.stale(e,t))}forget(e){typeof e=="string"&&this.#l(()=>{this.#f(oe.forget,[e])},t=>t.forget(e))}current(e){return this.#l(()=>this.#w(e)!==null&&this.#f(oe.current,[this.#w(e)]),t=>t.current(e))}choose(e,t,n){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(oe.current,[this.#w(o)])&&t(o)).map(o=>o.mediaType);return i.length===0?this.#b=null:this.#v(this.#a(oe.choose,[this.#B(e),i,!!n]))},s=>s.choose(e,t,n))}hinted(e,t){return this.#l(()=>{let n=this.#w(e);return n===null?this.#b=null:this.#v(this.#f(oe.hinted,[n,this.#B(t)]))},n=>n.hinted(e,t))}begin(e){return this.#l(()=>!e||e!==this.#b?null:(this.#b=null,this.#a(oe.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(oe.valid,[t])},t=>t.valid(e))}replaced(e,t){return this.#l(()=>{let n=e?this.#n.get(e):void 0;return n!==void 0&&this.#a(oe.replaced,[n,typeof t=="string"?t:null])},n=>n.replaced(e,t))}allocated(e,t){this.#l(()=>{e.dial=t,e.window.vacant=!1;let n=this.#n.get(e);n!==void 0&&this.#a(oe.allocated,[n,this.#O(t,!0)])},n=>n.allocated(e,t))}abandoned(e){this.#l(()=>{let t=e?this.#n.get(e):void 0;t!==void 0&&this.#a(oe.abandoned,[t])},t=>t.abandoned(e))}failed(e){this.#l(()=>{let t=this.#O(e,!1);t!==void 0&&this.#a(oe.failed,[t])},t=>t.failed(e))}end(e=this.window){return this.#l(()=>!!e&&e===this.#c&&this.#a(oe.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(oe.verified,[t])},t=>t.verified(e))}live(e=this.window){return this.#l(()=>!!e&&e===this.#c&&this.#f(oe.live,[]),t=>t.live(e))}reserved(){return this.#l(()=>this.#f(oe.reserved,[]),e=>e.reserved())}suppresses(e){return typeof e!="string"?!1:this.#l(()=>this.#f(oe.suppresses,[e]),t=>t.suppresses(e))}snapshot(){return this.#l(()=>({...this.#f(oe.snapshot,[]),counters:{...this.counters}}),e=>e.snapshot())}clear(){this.#l(()=>{this.#b=null,this.#S=null,this.#a(oe.clear,[])},e=>e.clear())}};var Pa=0,Ha=1,Da=2,Ua=3,_i=new TextEncoder,Ur=new TextDecoder;function za(r){return{sequence:r.frag.sn??null,discontinuity:r.frag.cc??0,part:r.part?.index??null,level:String(r.frag.level),fragType:r.frag.type??null,decryptMethod:r.frag.decryptdata?.method??null,media:_t(r)}}async function qa(r){if(r instanceof WebAssembly.Module)return{instance:await WebAssembly.instantiate(r,{}),module:r};if(r instanceof ArrayBuffer||ArrayBuffer.isView(r))return WebAssembly.instantiate(r,{});let e=r instanceof URL?r.href:r;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 Fa=["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"],Oi=13,ja=15,zr=13,Ci=zr*8,Wa=5,It=r=>Number.isNaN(r)?null:r,Ii=(r,e)=>new Float64Array(r.memory.buffer,e,6);function Un(r,e,t){let n=e.byteLength,s=r.rs_alloc(n);try{return new Uint8Array(r.memory.buffer,s,n).set(e),t(s,n)}finally{r.rs_free(s,n)}}var zn=(r,e)=>new Uint8Array(r.memory.buffer,r.rs_result_ptr(),e);function Ka(r,e){let t=zn(r,e),n=new DataView(t.buffer,t.byteOffset,e),s=new Array(zr);for(let o=0;oe)throw new Error("Core link frame has a truncated resolution.");i.push({tag:a,id:n.getFloat64(l,!0),payload:t[l+8]===1?t.slice(l+9,c):null})}return{header:s,events:i}}var qr=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(n){return this.#e=new wt,this.#t?.(n),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=>Ii(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 It(this.#o(0))}rate(){return It(this.#o(1))}observe({firstByteMs:e=null,bytes:t=0,flowMs:n=0,totalFlowMs:s=n}={}){this.#i(i=>i.rs_sel_observe(Date.now(),Number.isFinite(e)?e:NaN,t,n,s||0),i=>i.observe({firstByteMs:e,bytes:t,flowMs:n,totalFlowMs:s}))}record(e,t,n=0){this.#i(s=>s.rs_sel_record(Date.now(),this.#c(e),t,n),s=>s.record(e,t,n))}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(n=>{t!==void 0&&n.rs_sel_forget(t)},n=>n.forget(e))}projectMs(e){return this.#i(t=>It(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(n=>It(n.rs_sel_estimate(this.#c(e),t)),n=>n.estimate(e,t))}summary(e){return this.#i(t=>{let[n,s,i,o,a,l]=Ii(t,t.rs_sel_summary(this.#c(e)));return{attempts:n,latencyMs:It(s),throughputBytesPerSecond:It(i),failureRate:o,consecutiveFailures:a,lastSelected:l}},t=>t.summary(e))}select(e,t,n,s,i=1/0){return this.#i(o=>{let a=[...e].filter(u=>!u.closed&&!u.busy&&!n.has(u.pubkey)&&u.have.has(t)),l=a.map(u=>this.#c(u)),c=l.length*4,h=o.rs_alloc(c);try{let u=new DataView(o.memory.buffer,h,c);l.forEach((g,f)=>u.setUint32(f*4,g,!0));let p=o.rs_sel_select(h,l.length,s,i);return p<0?null:a[l.indexOf(p)]}finally{o.rs_free(h,c)}},o=>o.select(e,t,n,s,i))}};async function Ni(r,{onFailure:e}={}){let{instance:t,module:n}=await qa(r),s=t.exports;for(let m of["memory","rs_alloc","rs_free","rs_call","rs_result_ptr",...Fa])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[...h.links])m.die()}},c=m=>{if(!i){l();try{e?.(m)}catch{}}},h={links:new Set,rangeUploads:typeof s.rs_link_serve_range=="function",newLink(m,y,w,b,M){if(i)throw new Error("The core has been retired.");return s.rs_link_new(m,y,w,b?1:0,M)},free(m){if(!i)try{s.rs_link_free(m)}catch(y){c(y)}},call(m,y,w,b,M,R,Z){if(i)return null;try{let k=Un(s,Z,(C,U)=>y===ja&&h.rangeUploads?s.rs_link_serve_range(m,w,b,M,R,C,U):s.rs_link_call(m,y,w,b,M,R,C,U));if(k<0||ks.rs_link_call(m,Oi,0,0,0,0,w,b));if(y<0)throw new Error(`Core link ${m} refused operation ${Oi}.`);return JSON.parse(Ur.decode(zn(s,y)))}catch(y){return c(y),null}}};function u(m,y){let w;try{w=_i.encode(JSON.stringify(y))}catch{return null}let b=Un(s,w,(M,R)=>s.rs_call(m,M,R));return b<0?null:JSON.parse(Ur.decode(zn(s,b)))}function p(m,y,w){if(i)throw new Error("The core has been retired.");let b=_i.encode(JSON.stringify(w)),M=Un(s,b,(R,Z)=>s.rs_disc_call(m,y,R,Z));if(M<0)throw new Error(`Core discovery refused operation ${m}.`);return JSON.parse(Ur.decode(zn(s,M)))}let g=({streamEvent:m,swarmId:y,revokedDelegationIds:w=[],delegationRevocations:b=[]})=>({streamEvent:m,swarmId:y,revokedDelegationIds:w,delegationRevocations:b}),f=Object.freeze({kind:"wasm",validStreamAuthorisation:m=>u(Pa,[m])===!0,verifyCommitmentDelegation:(m,y,w=Date.now())=>u(Ha,[m??null,g(y),w]),verifySegmentCommitment(m,y,w=Date.now()){let b;try{b=za(y.context)}catch{return null}return u(Da,[m??null,{...g(y),key:y.key,context:b,maxSegmentBytes:y.maxSegmentBytes,delegation:y.delegation??null},w])}});return Object.freeze({module:n,verifier:f,playerHint(m){if(i)return null;try{return u(Ua,m)}catch(y){return c(y),null}},retire:l,get retired(){return i},peerSelection(){if(o)throw new Error("This core instance already has a peer selection.");return o=new qr(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 Dn(p,c,m)},peerLink(m){return new Hn(m,h)},transfer(m){return Ti(s,m,()=>i,c)}})}var Va=new Uint8Array(0);var $a=Object.freeze({maxTransfers:2,maxSegmentBytes:16777216,maxActiveBytes:33554432,maxPending:32,maxPendingBytes:33554432,initTimeoutMs:5e3,operationTimeoutMs:5e3}),Ga=Object.freeze({maxTransfers:4,maxSegmentBytes:32*1048576,maxActiveBytes:64*1048576,maxPending:128,maxPendingBytes:64*1048576,initTimeoutMs:3e4,operationTimeoutMs:3e4}),Pi=r=>typeof r=="string"&&r.length===64&&/^[a-f0-9]{64}$/.test(r),je=r=>Number.isSafeInteger(r)&&r>=0,tn=r=>Number.isFinite(r)&&r>=0&&r<=Number.MAX_SAFE_INTEGER,en=r=>r===null||tn(r),Ya=(r,e)=>r&&Array.isArray(r.commands)&&r.commands.length<=1024&&r.commands.every(t=>t&&["request","origin","cancel","abandon","ban","deliver","fail"].includes(t.t))&&(r.next===null||tn(r.next))&&typeof r.late=="boolean"&&typeof r.finished=="boolean"&&(r.verified===null||je(r.verified)&&r.verified<=e)&&(r.bytes===null||r.bytes instanceof Uint8Array&&r.bytes.byteLength<=e),fe=class extends Error{constructor(e){super(`Core transfer worker: ${e}.`),this.name="CoreTransferWorkerError",this.code=e}},Ct=()=>new DOMException("Core transfer was cancelled.","AbortError");function Za(r={}){let e={};for(let[t,n]of Object.entries($a)){let s=r[t]??n;if(!Number.isSafeInteger(s)||s<1||s>Ga[t])throw new fe("invalid-limits");e[t]=s}return Object.freeze(e)}function Xa(r,e){if(!r||!Array.isArray(r.pieces)||r.pieces.length<1||r.pieces.length>256)throw new fe("invalid-transfer");let t=r&&{size:r.size,sha256:r.sha256,pieces:r.pieces?.slice(),deadline:r.deadline,maxHolders:r.maxHolders,originReserveMs:r.originReserveMs,...r.peerOnly===!0?{peerOnly:!0}:{}};if(!t||!je(t.size)||t.size<1||t.size>e.maxSegmentBytes||!Pi(t.sha256)||!Array.isArray(t.pieces)||t.pieces.length<1||t.pieces.length>256||!t.pieces.every(Pi)||!tn(t.deadline)||!je(t.maxHolders)||t.maxHolders<1||t.maxHolders>32||!tn(t.originReserveMs)||r.peerOnly!==void 0&&typeof r.peerOnly!="boolean")throw new fe("invalid-transfer");return t}function Ja(r,e,t,n=!1){let[s,i,o]=e;if(!tn(s))throw new fe("invalid-operation");if(r==="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])&&en(l[1])&&en(l[2]))||(n?a.origin!=null:!Array.isArray(a.origin)||a.origin.length!==2||!a.origin.every(en))||!en(a.sharedFirstByteMs??null)||!en(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:n?null:[...a.origin],sharedFirstByteMs:a.sharedFirstByteMs??null,sharedRate:a.sharedRate??null,probePeers:[...a.probePeers??[]]}]}if(r==="tick")return[s];if(i!=="origin"&&!je(i))throw new fe("invalid-operation");if(n&&i==="origin")throw new fe("invalid-operation");if(r==="failed")return[s,i];if(r==="progress"&&je(o)&&o<=t)return[s,i,o];if(r==="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??((C,U)=>new Worker(C,U)),l;try{l=a(e,{type:"module",name:"relayswarm-transfer"})}catch{throw new fe("worker-unavailable")}let c="loading",h=null,u=0,p=0,g=0,f=0,m=new Map,y=new Map,w=C=>{C.signal?.removeEventListener("abort",C.onAbort),y.get(C.id)===C&&(y.delete(C.id),f-=C.size)},b=(C,U=!0)=>{if(!(c==="stopped"||c==="failed")){c=U?"failed":"stopped",h=C.code??C.name,l.removeEventListener("message",Z),l.removeEventListener("error",M),l.removeEventListener("messageerror",M),n?.removeEventListener("abort",R);for(let _ of m.values())clearTimeout(_.timer),_.settled||_.reject(C);m.clear(),g=0;for(let _ of y.values())_.closed=!0,w(_);try{l.terminate()?.catch?.(()=>{})}catch{}if(U)try{s?.(C)?.catch?.(()=>{})}catch{}}},M=C=>{C?.preventDefault?.(),b(new fe("worker-error"))},R=()=>b(Ct(),!1),Z=({data:C})=>{if(!C||C.v!==1||!je(C.id)||!m.has(C.id))return;let U=m.get(C.id);if(m.delete(C.id),g-=U.bytes,clearTimeout(U.timer),C.ok!==!0){let _=new fe(typeof C.error=="string"&&/^[a-z-]{1,40}$/.test(C.error)?C.error:"invalid-response");U.settled||U.reject(_),(C.fatal||C.ok!==!1)&&b(_)}else if(["init","new","free"].includes(U.op)?C.result!==!0:!Ya(C.result,U.size)){let _=new fe("invalid-response");U.settled||U.reject(_),b(_)}else U.settled||U.resolve(C.result)},k=(C,U,_,z=0,N=[],d=!1)=>c==="stopped"||c==="failed"?Promise.reject(new fe("closed")):!d&&m.size>=o.maxPending||g+z>o.maxPendingBytes?Promise.reject(new fe("queue-limit")):new Promise((x,A)=>{let v=++u,B={resolve:x,reject:A,handle:U,bytes:z,op:C,size:y.get(U)?.size??o.maxSegmentBytes,settled:!1,timer:setTimeout(()=>b(new fe(C==="init"?"init-timeout":"operation-timeout")),C==="init"?o.initTimeoutMs:o.operationTimeoutMs)};m.set(v,B),g+=z;try{l.postMessage({v:1,id:v,op:C,handle:U,input:_},N)}catch{b(new fe("worker-message"))}});l.addEventListener("message",Z),l.addEventListener("error",M),l.addEventListener("messageerror",M),n?.addEventListener("abort",R,{once:!0}),n?.aborted&&R();try{await k("init",null,{module:r,limits:o})}catch(C){throw b(C),C}if(c!=="loading")throw new fe("closed");return c="ready",Object.freeze({snapshot:()=>({state:c,reason:h,transfers:y.size,activeBytes:f,pending:m.size,pendingBytes:g}),stop:R,async transfer(C,{signal:U}={}){if(c!=="ready")throw new fe("closed");if(U?.aborted)throw Ct();let _=Xa(C,o);if(y.size>=o.maxTransfers||f+_.size>o.maxActiveBytes)throw new fe("transfer-limit");let z={id:++p,size:_.size,closed:!1,signal:U,release:null};y.set(z.id,z),f+=_.size;let N=()=>{if(z.release)return z.release;z.closed=!0;for(let x of m.values())x.handle===z.id&&!x.settled&&(x.settled=!0,x.reject(Ct()));return z.release=k("free",z.id,null,0,[],!0).then(()=>!0,()=>!1).finally(()=>w(z))};z.onAbort=()=>{N()},U?.addEventListener("abort",z.onAbort,{once:!0});try{await k("new",z.id,_)}catch(x){throw z.closed||w(z),x}if(z.closed||U?.aborted)throw N(),Ct();let d=async(x,A)=>{if(z.closed)throw new fe("closed-transfer");try{let v=Ja(x,A,o.maxSegmentBytes,_.peerOnly===!0),B=0,O=[];if(x==="delivered"){if(B=v[3].byteLength,g+B>o.maxPendingBytes)throw new fe("queue-limit");v[3]=v[3].slice(),O=[v[3].buffer]}let P=await k(x,z.id,v,B,O);if(z.closed)throw Ct();return P}catch(v){throw N(),v}};return Object.freeze({start:(x,A)=>d("start",[x,A]),delivered:(x,A,v,B)=>d("delivered",[x,A,v,B]),failed:(x,A)=>d("failed",[x,A]),progress:(x,A,v)=>d("progress",[x,A,v]),tick:x=>d("tick",[x]),free:N,cancel:N,get closed(){return z.closed}})}})}function Di(r,e,t){if(!Number.isSafeInteger(e)||!Number.isSafeInteger(t)||e<0||t<=e)return null;let n=Number.isSafeInteger(r?.rangeEnd)&&r.rangeEnd>0,s=n&&Number.isSafeInteger(r.rangeStart)?r.rangeStart:0;return n&&s+t>r.rangeEnd?null:{first:s+e,last:s+t-1}}function ht(r,e,t,n,s=null,i=null){if(typeof r=="function")try{let o=r({outcome:e,expectedBytes:Number.isSafeInteger(n-t)&&n>t?n-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 Ui(r,e,t,n,{signal:s,onIgnored:i,onResult:o}={}){let a=Di(e,t,n);return!a||typeof r?.Loader!="function"||typeof e?.url!="string"||s?.aborted?(ht(o,s?.aborted?"abort":"invalid-request",t,n),Promise.resolve(null)):new Promise(l=>{let c=null,h=!1,u=(f,m,y=f?.byteLength??null,w=null)=>{if(!h){h=!0,s?.removeEventListener("abort",p);try{c?.destroy?.()}catch{}ht(o,m,t,n,y,w),l(f)}},p=()=>{try{c?.abort?.()}catch{}u(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===n-t?m.slice():null};try{c=new r.Loader(r.config),s?.addEventListener("abort",p,{once:!0}),c.load({...e,responseType:"arraybuffer",rangeStart:a.first,rangeEnd:a.last+1},r.loaderConfig??{},{onSuccess:f=>{if(s?.aborted)return u(null,"abort");let m=g(f?.data);if(!m&&!h)try{i?.()}catch{}u(m,m?"payload":"wrong-size",f?.data?.byteLength??null,f?.code)},onError:f=>u(null,s?.aborted?"abort":"error",null,f?.code),onTimeout:()=>u(null,s?.aborted?"abort":"timeout"),onAbort:()=>u(null,"abort")})}catch{u(null,"exception")}})}function Qa(r,{first:e,last:t}){if(r===null)return!0;let n=/^bytes (\d+)-(\d+)\/(\d+|\*)$/u.exec(r.trim());return!!n&&Number(n[1])===e&&Number(n[2])===t}async function zi(r,e,t,{signal:n,onIgnored:s,onResult:i,fetchImpl:o=globalThis.fetch}={}){let a=Di(r,e,t);if(!a||typeof r?.url!="string"||typeof o!="function"||n?.aborted)return ht(i,n?.aborted?"abort":"invalid-request",e,t),null;let l;try{l=await o(r.url,{headers:{Range:`bytes=${a.first}-${a.last}`},signal:n,credentials:"same-origin"})}catch{return ht(i,n?.aborted?"abort":"error",e,t),null}let c=(h=null)=>{try{s?.()}catch{}return ht(i,"wrong-size",e,t,h,l.status),null};try{if(l.status!==206||!Qa(l.headers.get("content-range"),a)){try{await l.body?.cancel()}catch{}return l.status===200||l.status===206?c():(ht(i,"error",e,t,null,l.status),null)}let h=new Uint8Array(await l.arrayBuffer());return h.byteLength!==t-e?c(h.byteLength):(ht(i,"payload",e,t,h.byteLength,l.status),h)}catch{return ht(i,n?.aborted?"abort":"error",e,t,null,l?.status),null}}var Te=Symbol("relayswarm-warm-ahead"),We=24*1024*1024,qi=3,Fr=4,nn=8e3,el=100,dt=r=>{let{start:e,duration:t}=r?.context?.frag??{};return Number.isFinite(e)&&e>=0&&Number.isFinite(t)&&t>0&&Number.isFinite(e+t)},jr=(r,e)=>dt(r)&&r.context.frag.start<=e&&er?.key===e?.key&&r?.scope===e?.scope&&dt(r)&&dt(e)&&r.context.frag.start===e.context.frag.start&&r.context.frag.duration===e.context.frag.duration,tl=(r,e,t,n)=>{try{let{start:s,end:i}=r.loading;return r.aborted!==!0&&r.loaded===e&&[t,n,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(r.url??e.url),n=e.baseurl??e.base?.url;return!["http:","https:"].includes(t.protocol)||t.username||t.password||t.hash||typeof n!="string"?null:{context:{...r,url:t.href,frag:{sn:e.sn,cc:e.cc??0,type:e.type,level:e.level,url:t.href,baseurl:n,start:e.start,duration:e.duration,byteRangeStartOffset:e.byteRangeStartOffset,byteRangeEndOffset:e.byteRangeEndOffset},part:null,responseType:"arraybuffer"},key:JSON.stringify([t.href,n,e.type,e.level,e.sn,e.cc??0,0,0]),scope:JSON.stringify([n,e.type,e.level])}}catch{return null}}function Fi({Loader:r,next:e,authorise:t,verify:n,reserve:s=()=>!0,onVerified:i,onReuse:o,reuseBudget:a=()=>0,allowed:l=()=>!0,steady:c=!0,startupTarget:h=null,startupCommit:u=null,startupRecovery:p=()=>2e3}){let g=!1,f=0,m=null,y=null,w=[],b,M,R=null,Z=0,k=new Map,C=new Set,U=new Map,_=new Set,z=new Set,N=new Map,d={enabled:typeof h=="function",state:h?"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},A=()=>d.reserved+[...U.values()].reduce((S,E)=>S+E.reserved,0),v=()=>new Set([...k.keys(),...U.keys(),...d.owner?[d.own.key]:[]]).size,B=()=>d.state==="buffering"?Fr:qi,O=S=>U.get(S.key)===S&&!S.finished,P=S=>{let E=k.get(S);E&&(x.cacheBytes-=E.data.byteLength,k.delete(S))},T=(S,E)=>{O(S)&&(S.finished=!0,U.delete(S.key),_.delete(S),m===S&&(m=null),S.reserved=0,S.finish(E),d.checking&&(d.recheck=!0),W(),queueMicrotask(F))},D=S=>{O(S)&&(x.cancelled++,S.cancel(),T(S,null))},H=()=>{(d.state==="idle"||d.state==="buffering")&&Q("cancelled","cleared",!g),d.planningServiceMs=null,f++,w=[],R=null;for(let S of[...U.values()])D(S);for(let S of k.keys())P(S);for(let S of[...z])S(!0)},F=()=>{if(g||m||!l()||!w.length||C.size+_.size>1||!c&&d.state!=="buffering"||d.state==="buffering"&&(!d.permit||d.checking)||d.state==="buffering"&&!Wn()||d.state==="buffering"&&v()>=B())return;let S=w.shift();if(k.has(S.key)||U.has(S.key)){queueMicrotask(F);return}for(;v()>=qi&&k.size&&d.state!=="buffering";)P(k.keys().next().value);if(v()>=B())return;let E=new AbortController,q=f,Y=b,L=M,K,J,X,$={...S,reserved:0,finished:!1,waiters:new Set,genuineAt:null,promise:new Promise(te=>{X=te}),noteDemand(){$.genuineAt??=performance.now(),S.context[Te]?.onGenuine?.()},genuine(){if(!O($))return null;let te=[...$.waiters].find(xe=>xe.pendingTerminal&&Ae(xe.context)?.key===$.key);return te&&$.genuineAt!==null?{at:$.genuineAt,context:te.context}:null},promote(){clearTimeout(J)},finish:te=>X(te),cancel(){E.abort(),clearTimeout(J);try{K?.abort(),K?.destroy()}catch{}}};m=$,U.set($.key,$),J=setTimeout(()=>D($),nn),(async()=>{try{let te=await t(S.context,E.signal);if(E.signal.aborted||g||q!==f||!O($)||!l())return null;if(!te||!Number.isSafeInteger(te.size)||te.size<1||te.size>We)return x.rejected++,null;for(;x.cacheBytes+A()+te.size>We&&k.size&&d.state!=="buffering";)P(k.keys().next().value);if(x.cacheBytes+A()+te.size>We)return x.rejected++,null;if($.reserved=te.size,!s(A()))return $.reserved=0,x.rejected++,null;x.highWaterBytes=Math.max(x.highWaterBytes,x.cacheBytes+A());let xe=S.context[Te]={peerBytes:0,genuine:()=>$.genuine(),startupDependency:()=>{if(!j()||!O($)||!l()||!pe(S))return null;try{return me()===null||!j()?null:{at:d.entryAt,deadline:d.deadline,signal:d.controller.signal,context:S.context}}catch{return null}}};K=new r(Y),x.started++;let ue=performance.now(),he=await new Promise(le=>K.load(S.context,L,{onSuccess:(be,ce,Pe,Ce)=>le({response:be,stats:ce,details:Ce,serviceMs:tl(ce,te.size,ue,performance.now())}),onError:(...be)=>le({failure:{name:"onError",args:be,stats:K.stats}}),onTimeout:(...be)=>le({failure:{name:"onTimeout",args:be,stats:K.stats}}),onAbort:(...be)=>le({failure:{name:"onAbort",args:be,stats:K.stats}}),onProgress:be=>{if(be?.loaded>te.size){E.abort();try{K.abort()}catch{}le(null)}}}));if(he?.failure)return E.signal.aborted||g||q!==f||!O($)?null:(x.rejected++,he);if(!he||E.signal.aborted||g||q!==f||!O($)||!await n(te,he.response.data,S.context,E.signal))return x.rejected++,null;if(E.signal.aborted||g||q!==f||!O($))return null;let de=he.response.data;if(de.byteLength!==te.size)return x.rejected++,null;if($.reserved=0,i?.(te,de,S.context)===!1)return null;let ye={...he,context:S.context,scope:S.scope,data:de,permit:te,peerBytes:xe.peerBytes,accept:xe.accept};return k.set(S.key,ye),x.cacheBytes+=de.byteLength,x.verified++,x.verifiedBytes+=de.byteLength,x.verifiedPeerBytes+=xe.peerBytes,j()&&O($)&&f===q&&S.scope===y&&pe(S)&&(d.planningServiceMs=he.serviceMs),ye}catch{return E.signal.aborted||x.rejected++,null}finally{clearTimeout(J);try{K?.destroy()}catch{}}})().then(te=>T($,te))},ee=(S,E,q,Y)=>{R=null;let L=Ae(S);if(!L||g)return null;y!==L.scope&&(y!==null&&H(),y=L.scope),b=E,M=q;let K=[];try{K=e(S).map(Ae).filter(Boolean).filter(X=>X.scope===y).slice(0,2)}catch{}let J=new Set([L.key,...K.map(X=>X.key)]);for(let X of k.keys())J.has(X)||P(X);for(let X of[...U.values()])J.has(X.key)||D(X);return w=K,dt(L)&&K.every(dt)&&(R={own:ae(L),upcoming:K.map(ae),owner:Y}),L},j=()=>{if(d.state!=="buffering"||g||d.revision!==f||d.owner?.pendingTerminal!==d.terminal||d.terminal.settled)return!1;let S=!1;try{S=ut(Ae(d.terminal.context),d.identity)&&ut(Ae(d.own.context),d.identity)&&d.terminal.context.url===d.contextUrl&&d.terminal.context.frag.url===d.fragUrl}catch{}return S?!0:(Q("cancelled","context-changed"),!1)},V=S=>({code:0,text:"RelaySwarm startup buffer unavailable",startupBufferReason:S}),ne=S=>e(S.context).map(Ae).filter(Boolean).filter(E=>E.scope===y&&dt(E)).slice(0,2),ae=S=>{let{key:E,scope:q,context:{url:Y,frag:L}}=Ae(S.context);return{key:E,scope:q,context:{url:Y,frag:L,part:null,responseType:"arraybuffer"}}},ge=(S,E)=>({...ae(S),identity:ae(S),parent:ae(E)}),re=S=>{try{return ut(Ae(S.context),S.identity)&&ne(S.parent).some(E=>ut(E,S.identity))}catch{return!1}},pe=S=>{if(!j()||R?.owner!==d.terminal.id)return!1;let E=d.plan.find(q=>ut(q.identity,S));return!!(E&&re(E))},Q=(S,E,q=!0)=>{if(!["idle","buffering"].includes(d.state))return;let Y=d.owner,L=d.terminal;d.state=S,d.reason=E,S==="failed"&&d.failures++,S==="cancelled"&&d.cancellations++,clearTimeout(d.timer),d.timer=null,clearTimeout(d.poll),d.poll=null,d.controller?.abort(),d.releasePins?.(),d.owner=null,d.terminal=null,d.response=null,d.reserved=0,w=[],d.plan=[],d.cursor=null,d.frozenStart=null,d.planningServiceMs=null;for(let K of[...U.values()])D(K);for(let K of k.keys())P(K);if(!(!Y||!L||L.settled||Y.pendingTerminal!==L)){L.settled=!0,Y.pendingTerminal=null,Y.token++,Y.stats.aborted=!0;try{Y.inner.abort()}catch{}!q||g||(S==="cancelled"?L.callbacks.onAbort?.(Y.stats,L.context,null):L.callbacks.onError?.(V(E),L.context,null,Y.stats))}},me=()=>{let S;try{S=h()}catch{return Q("failed","target-threw"),null}return S===null?(Q("cancelled","target-unavailable"),null):!Number.isFinite(S)||S<0?(Q("failed","invalid-target"),null):(d.targetTime=S,S)},et=()=>{let S;try{S=p(d.own.context)}catch{}return!Number.isFinite(S)||S<0?(Q("failed","invalid-recovery"),null):(d.requiredHeadroomMs=S,S)},Ie=(S,E)=>{if(!j()||d.checking)return;if(d.frozenStart!==null&&S>=d.frozenStart&&(d.frozenStart=null),d.plan.some(L=>!re(L))||d.cursor&&!re(d.cursor))return Q("cancelled","context-changed");for(;d.plan.length;){let L=d.plan[0],K=k.get(L.key),J=U.get(L.key);if(L.context.frag.start+L.context.frag.duration>S||J||K&&N.has(K.permit.key)||[...C].some(X=>X.pendingTerminal&&Ae(X.context)?.key===L.key))break;if(!K){if(!d.hopAvailable)return;d.hopAvailable=!1}if(d.cursor=L,d.plan.shift(),w=w.filter(X=>X.key!==L.key),!j()||d.checking)return;P(L.key)}let q=d.plan[0];if(d.verified&&d.response&&d.plan.length===2&&k.size===2&&!m&&!U.size&&!C.size&&!_.size&&jr(q,S)&&d.plan.every(L=>k.has(L.key)&&!N.has(k.get(L.key).permit.key))){let L=St(S);L.end!==null&&(L.end-S)*1e3k.has(L.key)&&!N.has(k.get(L.key).permit.key))){let L=St(S);L.rows.length===d.plan.length+1&&L.end!==null&&(L.end-S)*1e3L.context.frag.start)?d.cursor:L??d.own,J;try{J=ne(K)[0]}catch{return Q("cancelled","context-changed")}if(!J)return;let X=K.context.frag.start+K.context.frag.duration;if(Math.abs(J.context.frag.start-X)>.001||J.key===d.own.key||d.plan.some(te=>te.key===J.key))return Q("cancelled","context-changed");let $=ge(J,K);if(J.context.frag.start+J.context.frag.duration<=S){if(!d.hopAvailable)return;d.hopAvailable=!1,d.cursor=$;return}d.plan.push($),w.push(J)}},Wn=()=>{if(!j()||d.checking)return!1;let S=me();if(S===null||!j())return!1;let E=et();if(E===null||!j()||(Ie(S,E),!j()||d.checking||!w.length))return!1;if(d.frozenStart!==null&&SS)return!0;let q=w[0],Y=d.plan.findIndex(L=>L.key===q.key);if(Y<0)return Q("cancelled","context-changed"),!1;if(q.context.frag.start+q.context.frag.duration<=S+(E+(d.planningServiceMs??0))/1e3){if(!d.hopAvailable)return!1;d.hopAvailable=!1,d.cursor=d.plan[Y],d.plan.splice(Y,1),w.shift(),Ie(S,E);let L=w[0]?.context.frag.start;return L>S&&(d.frozenStart=L),!1}return!0},ft=()=>{if(d.poll!==null||!j())return;let S=d.deadline-performance.now();if(S<=0)return Q("failed","deadline");d.poll=setTimeout(()=>{if(d.poll=null,!!j()){if(!d.checking){d.hopAvailable=!0;let E=me();if(E===null||!j())return;if(!l())return Q("cancelled","not-allowed");let q=et();if(q===null||!j()||(Ie(E,q),!j()))return;W(E),queueMicrotask(F)}ft()}},Math.min(el,S))},St=(S,E=null)=>{let q=d.verified&&d.response?[{...d.own,permit:d.permit}]:[],Y=(E??[...q,...k.values()]).filter(X=>X.scope===y&&dt(X)).sort((X,$)=>X.context.frag.start-$.context.frag.start),L=null,K=null,J=[];for(let X of Y){let $=X.context.frag.start,te=$+X.context.frag.duration;L===null?$<=S&&SK&&(K=te,J.push(X))}return d.verifiedStart=L,d.verifiedEnd=K,{start:L,end:K,rows:J}},rn=(S=void 0)=>{if(!j())return null;if(S===void 0&&(S=me()),S===null||!j())return;if(!l())return Q("cancelled","not-allowed");let E;try{E=p(d.own.context)}catch{}if(!Number.isFinite(E)||E<0)return Q("failed","invalid-recovery");d.requiredHeadroomMs=E;let q=St(S);if(!(q.end===null||(q.end-S)*1e3new Promise((E,q)=>{let Y=!1,L=J=>{Y||(Y=!0,S.removeEventListener("abort",K),J?E():q(null))},K=()=>L(!1);if(S.addEventListener("abort",K,{once:!0}),S.aborted)return K();try{Promise.resolve(u(Object.freeze({signal:S}))).then(()=>L(!0),()=>L(!1))}catch{L(!1)}}),W=async(S=void 0)=>{if(!j()||d.checking||!d.verified)return;let E=rn(S);if(!E)return;d.checking=!0;let q=d.owner,Y=d.terminal,L=f,K=new Map,J=[],X=!0,$=()=>{if(X){X=!1;for(let ue of J){let he=(N.get(ue)??0)-1;he>0?N.set(ue,he):N.delete(ue)}d.releasePins===$&&(d.releasePins=null)}};d.releasePins=$;let te=()=>[...K.values()].some(({key:ue,row:he,identity:de})=>k.get(ue)!==he||!ut(Ae(he.context),de)||he.data.byteLength!==he.permit.size)?(Q("failed","coverage-evicted"),!1):[...K.values()].some(({key:ue,row:he})=>!pe({key:ue,scope:he.scope,context:he.context}))?(Q("cancelled","context-changed"),!1):!0,xe=async({covered:ue})=>{for(let[ye,le]of k)ue.rows.includes(le)&&!K.has(le)&&(K.set(le,{key:ye,row:le,identity:Ae(le.context)}),J.push(le.permit.key),N.set(le.permit.key,(N.get(le.permit.key)??0)+1));let he=[{context:d.own.context,permit:d.permit},...ue.rows.filter(ye=>ye.context!==d.own.context)],de=await Promise.all(he.map(ye=>t(ye.context,d.controller.signal)));return()=>{if(!j()||f!==L)return;if(de.some((ce,Pe)=>!ce||ce.key!==he[Pe].permit.key||ce.size!==he[Pe].permit.size||ce.sha256!==he[Pe].permit.sha256))return Q("failed","authority-changed");let ye=me();if(ye===null||!j())return;if(!l())return Q("cancelled","not-allowed");let le;try{le=p(d.own.context)}catch{}if(!Number.isFinite(le)||le<0)return Q("failed","invalid-recovery");if(d.requiredHeadroomMs=le,de.some((ce,Pe)=>typeof ce.current!="function"||ce.current(he[Pe].context)!==!0))return Q("failed","authority-changed");if(!j())return;if(performance.now()>=d.deadline)return Q("failed","deadline");if(!te())return;let be=St(ye,ue.rows);if(!(be.end===null||(be.end-ye)*1e3=d.deadline)return Q("failed","deadline");if(d.commitCompleted=!0,!te())return;let le=rn();if(!le||(ue=await xe(le),!ue()))return}let he=d.response,de=Y.context[Te];if(o?.(Y.context,he[0].data.byteLength,de?.peerBytes??0),!j())return;if(!l())return Q("cancelled","not-allowed");if((de?.commit??de?.accept)?.(Y.context),!j())return;de?.peerBytes>0&&(x.consumedPeerBytes+=de.peerBytes),d.state="ready",d.reason=null,d.released++,d.planningServiceMs=null,clearTimeout(d.timer),d.timer=null,clearTimeout(d.poll),d.poll=null,d.reserved=0;let ye=d.controller;if(d.owner=null,d.terminal=null,d.response=null,d.plan=[],d.cursor=null,d.frozenStart=null,!c){w=[];for(let le of[...U.values()])D(le)}try{q.deliver(Y,"onSuccess",he)}finally{try{ye.abort()}finally{de?.notify?.()}}}catch{j()&&Q("failed","authority-refused")}finally{$(),d.checking=!1,d.state==="buffering"&&(queueMicrotask(F),d.recheck&&(d.recheck=!1,queueMicrotask(W)))}},ve=(S,E,q,Y)=>{if(!d.enabled)return!0;if(d.state==="failed"||d.state==="cancelled")return d.state==="cancelled"&&(S.stats.aborted=!0),S.deliver(E,d.state==="cancelled"?"onAbort":"onError",d.state==="cancelled"?[S.stats,E.context,null]:[V(d.reason),E.context,null,S.stats]),!1;if(!q)return d.state==="idle"&&E.context.frag?.type==="main"&&E.context.frag.sn!=="initSegment"?(d.state="failed",d.reason="unsupported-context",d.failures++,S.deliver(E,"onError",[V(d.reason),E.context,null,S.stats]),!1):!0;if(d.state==="buffering")return Q("cancelled","superseded"),S.deliver(E,"onAbort",[S.stats,E.context,null]),!1;if(d.state!=="idle")return!0;let L=performance.now(),K=Y?.loadPolicy?.maxLoadTimeMs??Y?.timeout;if(Object.assign(d,{state:"buffering",owner:S,terminal:E,own:q,revision:f,reserved:We,entryAt:L,identity:{key:q.key,scope:q.scope,context:{frag:{start:q.context.frag.start,duration:q.context.frag.duration}}},contextUrl:E.context.url,fragUrl:E.context.frag.url,controller:new AbortController,deadline:L+Math.min(nn,Number.isFinite(K)&&K>0?K:nn)}),d.plan=(R?.upcoming??[]).map(J=>ge(J,q)),R?.owner===E.id&&(R.rolling=d.plan),d.cursor=null,E.context[Te]={peerBytes:0,genuine:()=>j()?{at:L,context:E.context}:null},!dt(q)||!l())return Q("failed","not-allowed"),!1;if(S.config.progressive===!0)return Q("failed","progressive-unsupported"),!1;if(me()===null||!j())return!1;try{if(!s(A()))return Q("failed","reservation-refused"),!1}catch{return Q("failed","reservation-refused"),!1}return j()?l()?(d.timer=setTimeout(()=>Q("failed","deadline"),Math.max(0,d.deadline-performance.now())),ft(),Promise.resolve().then(()=>j()?t(q.context,d.controller.signal):null).then(J=>{if(j()){if(!J||!Number.isSafeInteger(J.size)||J.size<1||J.size>We)return Q("failed","first-authority-refused");if(d.permit=J,d.reserved=J.size,!s(A()))return Q("failed","reservation-refused");x.highWaterBytes=Math.max(x.highWaterBytes,x.cacheBytes+A()),ie(),queueMicrotask(F)}}).catch(()=>{j()&&Q("failed","first-authority-refused")}),!0):(Q("cancelled","not-allowed"),!1):!1},ie=async()=>{if(!(!j()||!d.response||!d.permit||d.verifying||d.verified)){d.verifying=!0;try{let S=d.response[0].data,E=d.permit;if(!(S instanceof ArrayBuffer)||S.byteLength!==E.size||!await n(E,S,d.own.context,d.controller.signal))return j()&&Q("failed","first-integrity");if(!j())return;d.verified=!0,x.verified++,x.verifiedBytes+=S.byteLength,x.verifiedPeerBytes+=d.terminal.context[Te]?.peerBytes??0,W()}catch{j()&&Q("failed","first-integrity")}finally{d.verifying=!1}}};return{Loader:class{static relayswarmShadow=!0;constructor(E){this.config=E,this.inner=new r(E),this.stats=this.inner.stats,this.context=null,this.token=0}load(E,q,Y){this.abort(),this.context=E;let L={id:++Z,context:E,callbacks:{...Y},settled:!1};this.pendingTerminal=L,Y={...Y};for(let xe of["onSuccess","onError","onTimeout","onAbort"])Y[xe]=(...ue)=>this.complete(L,xe,ue);let K=++this.token,J=ee(E,this.config,q,L.id),X=J&&k.get(J.key);if(!ve(this,L,J,q))return;let $=!X&&J&&U.get(J.key),te=X??$?.promise;if(te){$&&(x.coalesced++,$.waiters.add(this),this.warmPending=$,$.noteDemand(),m===$&&_.size===0&&(m=null,_.add($),$.promote(),x.promotions++)),this.reuseAbort=new AbortController;let xe=f,ue=null,he,de=null,ye=()=>K===this.token,le=()=>{if(clearTimeout(he),z.delete(be),de!==null){let ce=N.get(de)-1;ce>0?N.set(de,ce):N.delete(de),de=null}},be=(ce=!1)=>{if(ce&&(le(),this.reuseAbort.abort()),!ye()||ue||this.originStarted)return;this.originStarted=!0,clearTimeout(he);let Pe={...Y,onProgress:(...Ce)=>{!ye()||ue==="cache"||(Ce[2]?.byteLength>0&&(ue="origin",this.reuseAbort.abort(),le()),Y.onProgress?.(...Ce))}};for(let Ce of["onSuccess","onError","onTimeout","onAbort"])Pe[Ce]=(...Ht)=>{!ye()||ue==="cache"||(ue="origin",this.reuseAbort.abort(),le(),Y[Ce]?.(...Ht))};this.start(E,q,Pe,K)};this.cancelReuse=()=>{le(),this.reuseAbort.abort()},z.add(be),Promise.resolve(te).then(async ce=>{if(!ye())return;if(this.releasePending(),g||!ce||xe!==f)return be(!0);if(ce.failure){let{name:Gr,args:Kn,stats:Yr}=ce.failure;ue="origin",le(),this.reuseAbort.abort(),Yr&&Object.assign(this.stats,Yr),Gr==="onError"?Y.onError(Kn[0],E,Kn[2],this.stats):Y[Gr](this.stats,E,Kn[2]);return}de=ce.permit.key,N.set(de,(N.get(de)??0)+1);let Pe=Math.max(0,Math.min(25,a(E)||0));Pe>0?he=setTimeout(be,Pe):be();let Ce;try{Ce=await t(E,this.reuseAbort.signal)}catch{}if(!ye()||ue==="origin")return;if(g||xe!==f)return be(!0);if(!Ce||Ce.key!==ce.permit.key||Ce.size!==ce.permit.size||Ce.sha256!==ce.permit.sha256)return P(J.key),be();ue="cache",le(),this.originStarted&&this.inner.abort(),Object.assign(this.stats,ce.stats);let Ht=ce.data.slice(0);x.localReuseBytes+=Ht.byteLength,ce.accepted||(ce.accepted=!0,ce.accept?.(E),x.consumedPeerBytes+=ce.peerBytes),o?.(E,Ht.byteLength,ce.peerBytes),Y.onSuccess({...ce.response,data:Ht},this.stats,E,ce.details),queueMicrotask(F)})}else this.start(E,q,Y,K);queueMicrotask(F)}start(E,q,Y,L){C.add(this),C.size+_.size>1&&m&&D(m);let K=this.pendingTerminal,J=()=>{C.delete(this),queueMicrotask(F)},X={...Y};X.onProgress=(...$)=>{if(!(g||L!==this.token||!K||K.settled||this.pendingTerminal!==K)){if(d.owner===this&&($[0]?.loaded>(d.permit?.size??We)||$[2]?.byteLength>(d.permit?.size??We)))return Q("failed","first-oversize");if(d.owner===this&&$[2]!==null&&$[2]!==void 0){j();return}Y.onProgress?.(...$)}};for(let $ of["onSuccess","onError","onTimeout","onAbort"])X[$]=(...te)=>{J(),L===this.token&&Y[$]?.(...te)};this.inner.load(E,q,X)}releasePending(){let E=this.warmPending;this.warmPending=null,E&&(E.waiters.delete(this),E.waiters.size||E.context[Te]?.onGenuine?.(),_.has(E)&&!E.waiters.size&&D(E))}complete(E,q,Y){if(!(!E||E.settled||this.pendingTerminal!==E)){if(d.owner===this&&d.terminal===E&&d.state==="buffering"){if(q==="onSuccess"){let L=Y[0]?.data;if(!(L instanceof ArrayBuffer)||L.byteLength>(d.permit?.size??We))return Q("failed","first-oversize");d.response=Y,ie();return}d.state=q==="onAbort"?"cancelled":"failed",d.reason=q==="onAbort"?"origin-abort":"origin-error",q==="onAbort"?d.cancellations++:d.failures++,clearTimeout(d.timer),clearTimeout(d.poll),d.poll=null,d.controller?.abort(),d.releasePins?.(),d.owner=null,d.terminal=null,d.response=null,d.reserved=0,w=[],d.plan=[],d.cursor=null,d.frozenStart=null,d.planningServiceMs=null;for(let L of[...U.values()])D(L);for(let L of k.keys())P(L)}this.deliver(E,q,Y)}}deliver(E,q,Y){!E||E.settled||this.pendingTerminal!==E||(q!=="onSuccess"&&R?.owner===E.id&&(R=null),E.settled=!0,this.pendingTerminal=null,E.callbacks[q]?.(...Y))}cancel(E){let q=this.pendingTerminal;d.owner===this&&d.terminal===q&&Q("cancelled","caller-abort",!E&&!g),q&&R?.owner===q.id&&(R=null),this.token++,this.originStarted=!1,this.cancelReuse?.(),this.releasePending(),C.delete(this),q&&(this.stats.aborted=!0),E&&q&&(q.settled=!0,this.pendingTerminal=null);try{E?this.inner.destroy():this.inner.abort()}finally{E||this.complete(q,"onAbort",[this.stats,q?.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:H,startupSnapshot:()=>({enabled:d.enabled,state:d.state,reason:d.reason,heldObjects:d.state==="buffering"?v():0,heldBytes:d.state==="buffering"?x.cacheBytes+A():0,targetTime:d.targetTime,verifiedStart:d.verifiedStart,verifiedEnd:d.verifiedEnd,requiredHeadroomMs:d.requiredHeadroomMs,planningServiceMs:d.planningServiceMs,released:d.released,failures:d.failures,cancellations:d.cancellations,commitStarted:d.commitStarted,commitCompleted:d.commitCompleted,limits:{objects:Fr,bytes:We,deadlineMs:nn}}),contains(S){if(g||!l()||!Number.isFinite(S))return!1;for(let q of[...U.values(),...k.values()])if(q.scope===y&&jr(q,S))return!0;let E=R;if(!E||E.own.scope!==y||!jr(E.own,S))return!1;try{let q=E.rolling??e(E.own.context).map(Ae).filter(Boolean).filter(L=>L.scope===y).slice(0,2),Y=new Map([E.own,...q].map(L=>[L.key,L]));return(E.rolling?q.some(L=>!re(L)):q.length!==E.upcoming.length||q.some((L,K)=>!ut(L,E.upcoming[K])))||[...U,...k].some(([L,K])=>!ut({...K,key:L},Y.get(L)))?(R=null,!1):!0}catch{R=null}return!1},pinned:S=>N.has(S),release(S){for(let[E,q]of k)q.permit.key===S&&P(E)},stop(){g=!0,H()},snapshot:()=>({...x,reservationBytes:A(),active:+!!m,promoted:_.size,trackedObjects:v(),queued:w.length,cacheObjects:k.size,limits:{objects:B(),bytes:We,speculativeWholeRequests:1,deadlineMs:nn,revalidationMs:25}})}}function ji({now:r,take:e,give:t,delay:n,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},h=!1,u=null,p=w=>{if(!w.waiting)return;let b=Math.max(0,r()-w.queuedAt);c.waited++,c.waitTotalMs+=b,c.waitMaxMs=Math.max(c.waitMaxMs,b)},g=(w,b)=>{a.get(w.link)===w&&(a.delete(w.link),p(w),c[b]++,i(b),w.resolve(null))},f=(w,b=!1)=>{l.delete(w)&&(w.active=!1,b||t(w.charge),queueMicrotask(m))},m=()=>{if(clearTimeout(u),u=null,!h)for(;a.size;){let w=a.values().next().value;if(r()>=w.deadline){g(w,"expired");continue}if(!s(w)){g(w,"cancelled");continue}if(!e(w.charge)){w.waiting=!0;let b=w.deadline-r();u=setTimeout(m,Math.max(1,Math.ceil(Math.min(b,n(w.charge)))));return}a.delete(w.link),p(w),w.active=!0,w.controller=new AbortController,l.add(w),c.granted++,w.resolve(w)}},y=w=>{for(let b of[...a.values()])(!w||b.link===w)&&g(b,"cancelled");for(let b of[...l])(!w||b.link===w)&&(c.cancelled++,b.controller.abort(),f(b));m()};return{acquire(w,b){return h||a.has(w)||[...l].some(M=>M.link===w)||a.size>=o||!b.range&&(a.size||n(b.charge)>0)?(c.refused++,i("refused"),Promise.resolve(null)):new Promise(M=>{let R=r();a.set(w,{link:w,key:b.key,size:b.size,charge:b.charge,range:b.range?{start:b.range.start,end:b.range.end}:null,queuedAt:R,deadline:R+250,resolve:M,waiting:a.size>0,active:!1}),m()})},finish:f,cancel:y,recheck:m,stop(){h=!0,y(),clearTimeout(u),u=null},snapshot:()=>({enabled:!0,...c,queued:a.size,reservedBytes:[...l].reduce((w,b)=>w+b.charge,0),limits:{waitMs:250,waiters:o,perLink:1}})}}var rl=2,qn="webrtc",Wi=16,Wr=3e4,sl=1e4,Ki=300,Kr=32*1024,Vi=Object.freeze({mode:"shadow",originFallbackMs:1500,maxPeerWaitMs:5e3,originReserveMs:2e3,sustainablePeerWait:!1,warmAhead:!1,startupBufferTarget:null,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}),il=32768,ol=500,al=2e3,I=()=>performance.now(),Fn=r=>{let e=r?.loading?.first;return Date.now()-(Number.isFinite(e)&&e>0&&e<=I()?I()-e:0)},eo=r=>Array.from(new Uint8Array(r),e=>e.toString(16).padStart(2,"0")).join(""),$i=new TextEncoder;async function Nt(r){return eo(await globalThis.crypto.subtle.digest("SHA-256",r))}function Gi(r){return new URL(r,globalThis.location?.href).pathname}function ll(r){try{return new URL(r,globalThis.location?.href).origin}catch{return String(r)}}function _e(r,e){if(!r.length)return null;let t=[...r].sort((n,s)=>n-s);return Math.round(t[Math.min(t.length-1,Math.floor(e*t.length))])}function cl(r,e){if(!r.length)return null;let t=[...r].sort((n,s)=>n-s);return t[Math.min(t.length-1,Math.floor(e*t.length))]}function Vr(r){return{p50:_e(r,.5),p90:_e(r,.9)}}function Ke(r,e){r.push(e),r.length>ol&&r.shift()}function Pt(){let r=globalThis.navigator?.connection;return!!(r&&(r.type==="cellular"||r.saveData))}var jn=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"]}),Ve=r=>Math.min(Number.MAX_SAFE_INTEGER,r+1),Yi=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"]),Zi=Object.freeze(["payload","none","timeout","abort","abandoned","closed","busy","send-error"]),hl=15e3,ul=250,dl=50,Xi=Object.freeze(["presence","dialStart","offerBeforeSend","offerIncoming","answerIncoming","glareBeforeRollback","glareAfterRollback","answerBeforeSend","upload","refresh","other"]),fl=Object.freeze(["admission","not-held","not-serving","banned","session-allowance","peer-limit","rate-limit","reservation-refused","reservation-inactive"]);function Ji(r,e=1200,t,n){return new Promise(s=>{let i=c=>{try{n?.(c)}catch{}s(c)};if(r.iceGatheringState==="complete"||t?.aborted)return i(t?.aborted?"aborted":"complete");let o=()=>{clearTimeout(l),r.removeEventListener("icegatheringstatechange",a),t?.removeEventListener("abort",o);let c="unknown";try{c=t?.aborted?"aborted":r.iceGatheringState==="complete"?"complete":"capped"}catch{}i(c)},a=()=>{r.iceGatheringState==="complete"&&o()},l=setTimeout(o,e);r.addEventListener("icegatheringstatechange",a),t?.addEventListener("abort",o,{once:!0})})}async function pl(r){try{let e=await r.getStats(),t=null;return e.forEach(n=>{n.type==="transport"&&n.selectedCandidatePairId&&(t=e.get(n.selectedCandidatePairId)||t)}),t||e.forEach(n=>{n.type==="candidate-pair"&&n.state==="succeeded"&&(n.selected||n.nominated)&&(t=n)}),t?`${e.get(t.localCandidateId)?.candidateType||"?"}/${e.get(t.remoteCandidateId)?.candidateType||"?"}`:"unknown"}catch{return"unknown"}}function gl(){return eo(globalThis.crypto.getRandomValues(new Uint8Array(12)))}function Qi(r,{minLinkLifeMs:e,idleEvictMs:t,banned:n=new Set,tier:s}={},i=Date.now()){let o=null,a=0;for(let l of r){if(l.transferring||n.has(l.pubkey)||i-l.openedAttypeof i=="string"&&/^[0-9a-f]{64}$/u.test(i)).slice(0,e.maxReferrals):[];return{retryAfterMs:n,referrals:s}}function bl(r={}){let e=new $r(r);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 $r=class{constructor(e){this.options={...Vi,...e},this.options.iceTransportPolicy===void 0&&(this.options.iceTransportPolicy=Vi.iceTransportPolicy),this.startedAt=Date.now(),this.transportStartedAt=I(),this.transportSequence=0,this.transportRecords=[],this.transportDropped=0,this.transportCounters=Object.fromEntries(Object.entries(jn).map(([t,n])=>[t,Object.fromEntries(n.map(s=>[s,0]))])),this.transportConnections=new WeakMap,this.peerEligibilityRecords=[],this.peerEligibilityDropped=0,this.peerEligibilityCounters=Object.fromEntries(Yi.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(Zi.map(t=>[t,0])),this.uploadRefusalCounters=Object.fromEntries(fl.map(t=>[t,0])),this.admissionCallCounters=Object.fromEntries(Xi.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 Lt,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:n}=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(n==="off")return"mode-off";if(n!=="shadow"&&n!=="peer-first")return"invalid-mode";if(n==="peer-first"&&!Pn(this.options.streamEvent))return"invalid-stream-authorisation";if(n==="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&&(n!=="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>il)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&&(n!=="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&&(n!=="peer-first"||this.options.serve!==!0))return"invalid-warm-ahead-option";if(this.options.startupBufferTarget!==null&&(typeof this.options.startupBufferTarget!="function"||n!=="peer-first"||this.options.serve!==!0))return"invalid-startup-buffer-target";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&&!we(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.#Je(t),this.options.warmAhead||this.options.startupBufferTarget){this.warmAhead=Fi({Loader:e.config.fLoader,steady:this.options.warmAhead,startupTarget:this.options.startupBufferTarget,startupCommit:this.options.startupBufferCommit,startupRecovery:i=>Math.max(this.options.originReserveMs,(_e(this.#W(i),.9)||0)*1.25+100),allowed:()=>this.#p()&&e.media?.paused!==!0&&!Pt(),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.#R(i),l=await at(u=>this.options.getCommitment(i,{signal:u}),o,1e3);if(o.aborted||this.stopped)return null;let c=u=>!this.stopped&&this.#ce(l,{streamEvent:this.options.streamEvent,swarmId:this.options.swarmId,key:a,context:u,maxSegmentBytes:this.options.maxSegmentBytes,delegation:this.options.delegation,revokedDelegationIds:this.options.revokedDelegationIds,delegationRevocations:this.options.delegationRevocations}),h=c(i);return h&&h.size<=this.options.maxHeldBytes?{...h,key:a,current:u=>{let p=c(u);return!!(p&&p.size===h.size&&p.sha256===h.sha256)}}:null},verify:async(i,o,a,l)=>o instanceof ArrayBuffer&&o.byteLength===i.size&&!l.aborted&&await Nt(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,(_e(this.#W(i),.9)||0)*1.25+100);for(let c=0;ca)return Math.min(25,Math.max(0,(h-a)*1e3-l))}}catch{}return 0},onVerified:(i,o)=>(this.#nt(i.key),this.#z(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 n=e.media,s=()=>this.warmAhead?.clear();for(let i of["pause","ended"])n?.addEventListener?.(i,s,{signal:this.lifecycle.signal});n?.addEventListener?.("seeking",()=>{try{let i=n.currentTime;for(let o=0;o{n=o}),i=this.#h(al,n);this.coreRelease=n,this.coreWait=s.then(()=>{clearTimeout(i),this.timers.delete(i),this.coreWait=null,this.coreRelease=null}),this.#n("core",()=>this.#it().finally(n))}this.#n("start",()=>this.#lt()),typeof this.options.onMetrics=="function"&&this.#k(this.options.metricsIntervalMs,0,()=>this.options.onMetrics(this.metrics()))}catch(t){this.#o("attach",t)}}#t(e){let t=this,n=e.trigger;typeof n=="function"&&(this.originalTrigger=n,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 n.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 n.call(this,s,i)}finally{for(let[c,h]of l)h?Object.defineProperty(o,c,h):delete o[c]}},e.trigger=this.withheldTrigger)}updateTicket(e){return this.stopped||this.disabledReason||!this.#G()||!we(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.#F(),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.#se(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=Ve(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,n,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(n),budgetGeometry:{...s}}),i}catch{}}#c(e,t,n){if(!this.options.traceRequests)return null;let s=I(),i=this.traceBase,o=!1,a=!1,l=!1,c=!1,h=g=>{let f=g;try{f??=n()}catch{}let m=y=>{try{let w=f?.[y];return Number.isSafeInteger(w)&&w>=0?w:null}catch{return null}};return{loaderLoadedBytes:m("loaded"),loaderTotalBytes:m("total")}},u=(g,f)=>this.#e({k:g,load:e,leg:t,at:this.#s(),ms:Math.round(I()-s),ranged:!1,...f});return u("originStart",{}),{progress:(g,f,m)=>{if(m){c||(c=!0,u("originCallback",{phase:"progress",outcome:null,stale:!0}));return}a||f!==!0||(a=!0,u("originProgress",{stale:!1,...h(g)}))},abortRequest:g=>{o||l||(l=!0,u("originAbortRequest",{reason:g,...h()}))},terminal:(g,f=null,m,y=!1)=>p(g,f,m,y)};function p(g,f,m,y){if(o){c||(c=!0,u("originCallback",{phase:"terminal",outcome:g,stale:!0}));return}o=!0;let w=y?{loaderLoadedBytes:null,loaderTotalBytes:null}:h(m);u("origin",{at:Math.floor(s)-i,outcome:g,bytes:Number.isSafeInteger(f)&&f>=0?f:null,stale:y,...w})}}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",n=t?e.peerInTime+e.peerLate+e.peerMiss+e.peerCorrupt:0,s=n+e.noPeers,i=(o,a)=>a?Number((o/a).toFixed(3)):null;return{v:rl,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.#D(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:_e(this.signallingSamples,.5),p90Ms:_e(this.signallingSamples,.9),clock:{...this.session?this.session.clockDiagnostics():{aheadRejected:null,staleRejected:null,maxAheadSeconds:null,signalSamples:null,signalAgeMedianSeconds:null},origin:Xr(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,n),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:_e(this.peerLatencySamples,.5),peerLatencyP90Ms:_e(this.peerLatencySamples,.9),originLatencyMedianMs:_e(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.#P(),uploadExhausted:this.#P()===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.#L(),...this.multiHolder,originRangeOutcomes:{...this.originRangeOutcomes},timings:{durationMs:Vr(this.multiHolderTimings.map(o=>o[0])),slowestRequestMs:Vr(this.multiHolderTimings.map(o=>o[1])),requests:Vr(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 n=t();n&&typeof n.catch=="function"&&n.catch(s=>this.#o(e,s))}catch(n){this.#o(e,n)}}#h(e,t){if(this.stopped)return null;let n=setTimeout(()=>{this.timers.delete(n),this.stopped||this.#n("timer",t)},Math.max(0,e));return this.timers.add(n),n}#k(e,t,n){let s=()=>{let i=e*t*(Math.random()*2-1);this.#h(e+i,()=>{try{n()}finally{s()}})};s()}#M(e,t){try{let n=Zr(e,t);if(n===null)return;this.originClockSamples.push(n),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.#ze(s,a);if(t.#Y(s),t.options.peerSupplyHint&&t.#n("player-hint",()=>t.#B(s,l)),t.stopped||!s.frag||s.frag.sn==="initSegment"||s.part&&!t.options.swarmParts||!t.options.serveOnCellular&&Pt())return this.inner.load(s,i,o);if(l===0&&t.options.zeroBudgetPeerRace&&!this.hlsConfig.progressive&&t.#L()&&t.#l()){let k=new Map([...t.links.values()].filter(C=>t.#K(C,s)&&C.supportsRanges&&(t.remoteFraming.get(C.pubkey)??1)>=2&&!t.banned.has(C.pubkey)&&(C.have.size||t.options.lateHaveRace)).map(C=>[C,new Set(C.have)]));if(k.size)return this.loadCachedRace(s,i,o,a,k)}let c=i?.loadPolicy?.maxLoadTimeMs??i?.timeout;if(l===0&&t.options.latePeerRace&&!this.hlsConfig.progressive&&Ae(s)&&Number.isFinite(c)&&c>0&&t.#l())return this.loadLatePeerRace(s,i,o,a,c);let h=new AbortController,u={};this.active=u;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",y)};this.cancel=()=>{let k=this.active===u;return this.active=null,m(),h.abort(),k};let y=()=>{if(this.active!==u)return;this.active=null,this.pendingCallbacks=null,m(),h.abort(),t.counters.originFallbacks+=1,this.inner.stats.loading.start=0;let k=I(),C=!1;t.#R(s).then(z=>{!C&&!t.stopped&&(this.releaseFetch=t.#Z(z))}).catch(()=>{});let U=()=>{C=!0,this.releaseFetch?.(),this.releaseFetch=null},_=this.originTrace=t.#c(f,"fallback",()=>this.inner.stats);this.inner.load(s,i,{...o,onError:(...z)=>{_?.terminal("error",null,void 0,_!==this.originTrace),U(),o.onError?.(...z)},onTimeout:(...z)=>{_?.terminal("timeout",null,z[0],_!==this.originTrace),U(),o.onTimeout?.(...z)},onAbort:(...z)=>{_?.terminal("abort",null,z[0],_!==this.originTrace),U(),o.onAbort?.(...z)},onSuccess:(z,N,d,x)=>{let A=Fn(N),{copy:v,size:B}=t.#S(z,s);if(_?.terminal("payload",B||null,N,_!==this.originTrace),C=!0,Ke(t.originLatencySamples,I()-k),t.#X(t.renditionOriginSamples,s,I()-k),t.options.peerSupplyHint&&B){let O=t.#v(s);!t.hintSizes.has(O)&&t.hintSizes.size>=16&&t.hintSizes.delete(t.hintSizes.keys().next().value),t.hintSizes.set(O,B);let P=I()-k;P>0&&Ke(t.hintOriginRates,B/P)}o.onSuccess(z,N,d,x),t.#M(x,A),B&&!t.stopped?t.#n("peer-first-origin",async()=>{t.counters.originLoaded+=1,t.counters.bytesFromOrigin+=B;try{let O=await t.#R(s);v&&!t.stopped&&t.#z(O,new Uint8Array(v))}finally{U()}}):U()}})};if(l===0)return f=t.#i(s,0,0,a),t.#E(s,l,"no-budget",null,a),y();let w=()=>{Z.onDeadline?.()||(Z.expired=!0,y())};g=setTimeout(w,l),t.lifecycle.signal.addEventListener("abort",y,{once:!0});let b=Math.max(t.options.originFallbackMs,t.options.maxPeerWaitMs),M=Math.max(l,Math.min(b,a.uncappedMs??l,a.sustainableMs??1/0));f=t.#i(s,l,M,a);let R={Loader:e,config:this.hlsConfig,loaderConfig:i},Z={deadline:p+l,limit:p+M,originReserveMs:a.originReserveMs??t.options.originReserveMs,expired:!1,onDeadline:null,origin:R,extend:k=>{let C=Math.min(Z.limit,k);return this.active!==u||C<=Z.deadline?!1:(Z.deadline=C,clearTimeout(g),g=setTimeout(w,Math.max(0,C-I())),!0)}};t.#ae(s,h.signal,Z,l,a).then(k=>{if(!(this.active!==u||h.signal.aborted||t.stopped)){if(k&&!k.multi&&I()>=Z.deadline&&t.#C(k.demand),!k||I()>=Z.deadline&&!k.multi)return y();this.active=null,this.pendingCallbacks=null,m(),t.#O(this,k,s,o,p)}}).catch(k=>{this.active===u&&(t.#o("peer-first",k),y())})}loadCachedRace(s,i,o,a,l){let c=t.#i(s,0,t.options.maxPeerWaitMs,a),h={},u=new AbortController,p=I(),g=!0,f=!1,m;this.active=h,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 y=()=>{clearTimeout(m),t.lifecycle.signal.removeEventListener("abort",y),t.cachedRaces.delete(u),u.abort()};t.cachedRaces.add(u),t.lifecycle.signal.addEventListener("abort",y,{once:!0}),this.cancel=()=>{let R=g&&this.active===h;g=!1,this.active=null,y();try{this.inner.abort()}catch{}return R};let w=()=>!g||this.active!==h?!1:(g=!1,this.active=null,this.pendingCallbacks=null,y(),this.releaseFetch?.(),this.releaseFetch=null,!0);m=setTimeout(y,t.options.maxPeerWaitMs),t.counters.originFallbacks+=1,t.#E(s,0,"no-budget",null,a);let b=this.originTrace=t.#c(c,"cached",()=>this.inner.stats);try{this.inner.load(s,i,{...o,onProgress:(...R)=>{if(!g||this.active!==h){b?.progress(void 0,null,!0);return}let Z=R[2]?.byteLength>0;Z&&(f=!0,y()),b?.progress(R[0],Z,!1),o.onProgress?.(...R)},onError:(...R)=>{b?.terminal("error",null,void 0,!g||this.active!==h),w()&&o.onError?.(...R)},onTimeout:(...R)=>{b?.terminal("timeout",null,R[0],!g||this.active!==h),w()&&o.onTimeout?.(...R)},onAbort:(...R)=>{b?.terminal("abort",null,R[0],!g||this.active!==h),w()&&o.onAbort?.(...R)},onSuccess:(R,Z,k,C)=>{if((!g||this.active!==h)&&b?.terminal("payload",null,void 0,!0),!w())return;let U=Fn(Z),{copy:_,size:z}=t.#S(R,s);b?.terminal("payload",z||null,Z),Ke(t.originLatencySamples,I()-p),t.#X(t.renditionOriginSamples,s,I()-p),o.onSuccess(R,Z,k,C),t.#M(C,U),z&&!t.stopped&&t.#n("cached-race-origin",async()=>{t.counters.originLoaded+=1,t.counters.bytesFromOrigin+=z;let N=await t.#R(s);_&&!t.stopped&&t.#z(N,new Uint8Array(_))})}})}catch(R){throw w(),R}if(!g)return;t.#R(s).then(R=>{g&&!t.stopped&&(this.releaseFetch=t.#Z(R))}).catch(()=>{});let M={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,u.signal,M,0,a).then(R=>{if(!(!R||!g||f||this.active!==h||u.signal.aborted||t.stopped||I()>=M.limit)){g=!1,this.active=null,this.pendingCallbacks=null,y(),this.releaseFetch?.(),this.releaseFetch=null,b?.abortRequest("peer-won");try{this.inner.abort()}catch{}t.counters.zeroBudgetPeerRaceWins+=1,t.#O(this,R,s,o,p)}}).catch(R=>{g&&!u.signal.aborted&&!t.stopped&&t.#o("cached-race",R)}).finally(y)}loadLatePeerRace(s,i,o,a,l){let c=t.#i(s,0,l,a),h={},u=new AbortController,p=I(),g=!0,f=!1,m;this.active=h,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 y=()=>g&&!f&&this.active===h&&!t.stopped,w=M=>!g||this.active!==h?!1:(g=!1,this.active=null,this.pendingCallbacks=null,m?.close(M),this.releaseFetch?.(),this.releaseFetch=null,!0);this.cancel=()=>{let M=g&&this.active===h;g=!1,this.active=null,m?.close("caller-abort"),this.releaseFetch?.(),this.releaseFetch=null;try{this.inner.abort()}catch{}return M};let b;m=t.#w({context:s,controller:u,entryAt:p,parentDeadline:p+l,current:y,arm:(M,R)=>(t.options.traceRequests&&t.traceLoads.set(M,c),t.#ae(M,u.signal,R,0,a).then(Z=>{if(!Z||!y()||u.signal.aborted||I()>=R.limit||!m.valid()||typeof R.revalidateAuthority!="function"||!R.revalidateAuthority())return!1;g=!1,this.active=null,this.pendingCallbacks=null,m.close("peer-won","won"),this.releaseFetch?.(),this.releaseFetch=null,b?.abortRequest("peer-won");try{this.inner.abort()}catch{}return t.counters.zeroBudgetPeerRaceWins++,t.#O(this,Z,s,o,p),!0}))}),t.counters.originFallbacks++,t.#E(s,0,"no-budget",null,a),b=this.originTrace=t.#c(c,"late",()=>this.inner.stats);try{this.inner.load(s,i,{...o,onProgress:(...M)=>{if(!g||this.active!==h){b?.progress(void 0,null,!0);return}let R=M[2]?.byteLength>0;R&&(f=!0,m?.close("origin-progress")),b?.progress(M[0],R,!1),o.onProgress?.(...M)},onError:(...M)=>{b?.terminal("error",null,void 0,!g||this.active!==h),w("origin-error")&&o.onError?.(...M)},onTimeout:(...M)=>{b?.terminal("timeout",null,M[0],!g||this.active!==h),w("origin-timeout")&&o.onTimeout?.(...M)},onAbort:(...M)=>{b?.terminal("abort",null,M[0],!g||this.active!==h),w("origin-abort")&&o.onAbort?.(...M)},onSuccess:(M,R,Z,k)=>{if((!g||this.active!==h)&&b?.terminal("payload",null,void 0,!0),!w("origin-success"))return;let C=Fn(R),{copy:U,size:_}=t.#S(M,s);b?.terminal("payload",_||null,R),Ke(t.originLatencySamples,I()-p),t.#X(t.renditionOriginSamples,s,I()-p),o.onSuccess(M,R,Z,k),t.#M(k,C),_&&!t.stopped&&t.#n("late-race-origin",async()=>{t.counters.originLoaded++,t.counters.bytesFromOrigin+=_;let z=await t.#R(s);U&&!t.stopped&&t.#z(z,new Uint8Array(U))})}})}catch(M){throw w("origin-throw"),M}g&&m?.keyPromise.then(M=>{g&&this.active===h&&!t.stopped&&(this.releaseFetch=t.#Z(M))}).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 n=e.data,s=n?.byteLength;return s?{copy:this.#xe()&&!t?.[Te]?n.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:n,...e.dependencyAt!==null?{startupDependencyAtMs:o(e.dependencyAt),startupDeadlineAtMs:o(e.dependencyDeadline)}:{},...s?{holders:s.map(a=>this.#D(a.pubkey))}:{}})}#a(e){for(let t of[...this.latePeerOwners.values()])t.close(e)}#A(){for(let e of[...this.latePeerOwners.values()])e.refresh()}#w(e){let t=Ae(e.context);if(!t||!this.#l())return null;let n=e.context[Te],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(),n?.onGenuine===o.refresh&&delete n.onGenuine,this.latePeerOwners.delete(o.id),this.cachedRaces.delete(o.controller),o.controller.abort(),this.#f(o,g,p))};let c=()=>{let p=n?n.genuine?.():{at:s,context:e.context};if(p)return{...p,role:"genuine"};let g=n?.startupDependency?.();return g&&Number.isFinite(g.at)&&Number.isFinite(g.deadline)&&g.signal?.aborted===!1?{...g,role:"startup-buffer-dependency"}:null},h=(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),u=()=>{let p=c();return!p||!Number.isFinite(p.at)||Ae(p.context)?.key!==t.key?null:n?{...p.context,[Te]:n}:p.context};o.valid=()=>!o.closed&&e.current()&&!this.stopped&&o.generation===this.latePeerGeneration&&o.streamId===this.options.streamEvent?.id&&u()!==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=u();if(!g||i?.paused||i?.ended)return o.close("context-or-playback");if(o.windowEnd===null){let y=p.role==="startup-buffer-dependency";o.genuineAt=y?null:p.at,o.dependencyAt=y?s:null,o.dependencyDeadline=y?p.deadline:null,o.windowEnd=Math.min(e.parentDeadline,y?p.deadline:1/0,(y?s:p.at)+Math.min(4e3,this.options.lateWindowMs)),y&&p.signal.addEventListener("abort",()=>o.close("startup-buffer-ended"),{once:!0,signal:a.signal}),this.#f(o,"entered",y?"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.#L())return;let f=[...this.links.values()].filter(y=>h(y,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 y=await Promise.all(f.map(async k=>{if(!this.options.admit)return k;let C=this.admissionChecks.get(k.pubkey)?.ticket??this.admitted.get(k.pubkey)?.ticket,U=!1;try{U=await at(()=>this.#x(k.pubkey,C,"other"),o.controller.signal,Math.max(0,Math.min(this.options.admissionTimeoutMs,m-I())))===!0}catch{}return!U&&!o.closed&&k.close("admission"),U?k:null}));if(o.closed)return;let w=u();if(!e.current()||!w||I()>=m||o.generation!==this.latePeerGeneration)return o.close("inactive-after-admission");let b=y.filter(k=>k&&h(k,w));if(!b.length)return o.close("admission-or-have-refused","refused");o.validatedPeers=new Map(b.map(k=>[k,this.admitted.get(k.pubkey)?.ticket]));let M=Ae(w)?.context;if(!M||!o.valid())return o.close("context-after-admission");let R={deadline:m,limit:m,originReserveMs:0,expired:!1,onDeadline:null,knownKey:o.key,cachedOnly:new Map(b.map(k=>[k,new Set([o.key])])),lateHaveRace:!1,peerOnly:!0,extend:()=>!1,currentValid:o.valid,revalidateAuthority:!0};!await e.arm(M,R)&&!o.closed&&o.close("peer-no-result","refused")})().catch(()=>{o.closed||o.close("peer-error","refused")})},this.latePeerOwners.set(o.id,o),n&&(n.onGenuine=o.refresh);for(let p of["pause","ended","emptied"])i?.addEventListener?.(p,()=>o.close(`media-${p}`),{signal:a.signal});return o.keyPromise=this.#R(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,n,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.#F(),this.firstPeerSegmentAtMs===null&&(this.firstPeerSegmentAtMs=Date.now()-this.startedAt),Ke(this.peerLatencySamples,o-i),p.frag&&this.peerFragments.add(p.frag)}},h=()=>{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{}}},u=p=>{c(p),h()};n[Te]?Object.assign(n[Te],{peerBytes:l,accept:u,commit:c,notify:h}):u(n),!n[Te]&&this.#p()&&!this.held.has(t.key)&&this.#z(t.key,t.bytes.slice()),s.onSuccess({url:n.url,data:t.bytes.buffer,code:200},e.peerStats,n,null)}async#B(e,t){if(!e?.frag||e.frag.sn==="initSegment"||e.part||this.stopped)return;let n=++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(h=>h.sn===e.frag.sn&&h.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}`,h=a?await this.#R(a):null;if(this.stopped||n!==this.hintGeneration)return null;let u=a&&this.discovery.contexts.get(a.frag.type||"main"),p=h?[...this.links.values()].filter(M=>this.#N(M)&&M.have.has(h)&&M.supportsRanges===!0&&(this.remoteFraming.get(M.pubkey)??1)>=2&&!this.banned.has(M.pubkey)&&!(u?.rendition===c&&this.discovery.stale(u,M.pubkey))).map((M,R)=>{let Z=this.peerSelection.summary(M).throughputBytesPerSecond;return[R+1,null,Z?Z/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),y=_e(this.renditionOriginSamples.get(c)||[],.5),w={rendition:c,size:m,peers:p,origin:[null,m&&y?m/y:_e(this.hintOriginRates,.5)],sharedFirstByteMs:this.peerSelection.firstByteMs(),sharedRate:this.peerSelection.rate(),availableMs:t,maxHolders:this.options.maxHoldersPerObject},b=this.core?.playerHint(w);return b&&this.options.traceRequests&&this.#e({k:"playerHint",at:this.#s(),input:w,out:b}),b?{...b,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||n!==this.hintGeneration||(this.playerHints=o.filter(Boolean),this.playerHints.length&&this.options.onPlayerHint?.(structuredClone(this.playerHints)))}#v(e){let t=_t(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=Ae(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 n=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,!n)for(let s of this.links.values())s.sendContribution(this.#p(),t)}#I(e,t,n){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=n?.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,h)=>(parseInt(c,16)^parseInt(e[h],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 n=!1;return()=>{if(n)return;n=!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)}}}#ze(e,t){if(e?.[Te])return t.source="warm-ahead",0;let n=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=_e(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(!n)return t.source="no-media",Math.min(this.options.originFallbackMs,s);try{for(let i=0;in.currentTime){let o=Math.max(this.options.originReserveMs,(_e(this.#W(e),.9)||0)*1.25+100),a,l,c,h=(a=e?.part?.start)??e?.frag?.start,u=Number.isFinite(h)&&h>n.currentTime?Math.min(l=n.buffered.end(i),h):l=n.buffered.end(i),p=Math.max(0,(u-(c=n.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(u),fragmentStart:f(h),originReserveMs:f(o),uncappedMs:f(p)})}catch{}return g}}catch{return t.source="error",0}return t.source="no-buffer",0}async#R(e){let t=(this.options.segmentKey||Gi)(e.url||e.frag.url,e);if(typeof t!="string"||!t)throw new Error("Invalid segment key.");let n=e.rangeEnd?`#${e.rangeStart||0}-${e.rangeEnd}`:"";return Nt($i.encode(`${this.options.swarmId} -${t}${n}`))}#qe(e){if(this.holderLabels.has(e)||(this.holderLabels.set(e,this.holderLabelNext++),this.holderLabels.size<=64))return;let t=[...this.holderLabels.keys()].find(n=>!this.links.has(n))??this.holderLabels.keys().next().value;this.holderLabels.delete(t)}#D(e){return this.holderLabels.get(e)??0}#Fe({key:e,rendition:t,context:n}){let s=l=>l.sort((c,h)=>c-h).slice(0,8),i=[],o=[],a=[];for(let l of this.links.values()){let c=this.#D(l.pubkey);this.#q(l,t)&&(i.push(c),this.discovery.stale(n,l.pubkey)&&a.push(c)),l.have.has(e)&&o.push(c)}return{holders:s(i),haveHolders:s(o),staleHolders:s(a),heldMissHolders:[]}}#C(e,{everyServing:t=!1,unfit:n=[]}={}){let{key:s,rendition:i,context:o}=e;if(!(!o||e.recorded)){e.recorded=!0;try{let a=[...this.links.values()].filter(h=>this.#q(h,i));if(t&&![...this.links.values()].some(h=>h.have.has(s))){for(let h of a)this.discovery.holderMiss(o,h.pubkey,s);return}let l=a.filter(h=>e.asked.has(h.pubkey)||n.includes(h.pubkey)),c=[];for(let h of l)this.discovery.holderMiss(o,h.pubkey,s)&&(this.discovery.counters.heldMiss++,c.push(this.#D(h.pubkey)));c.length&&e.row?.heldMissHolders&&(e.row.heldMissHolders=c.sort((h,u)=>h-u).slice(0,8))}catch{}}}#je(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,n=>this.#Te(n))&&this.discovery.counters.staleBlocked++}#E(e,t,n,s,i,o,a,l=!1,c){try{if(!Yi.includes(n))return;let h=m=>Number.isSafeInteger(m)&&m>=0?m:null,u=null,p=null;try{u=h(e?.frag?.cc)}catch{}try{p=h(e?.frag?.level)}catch{}let g=I()-this.transportStartedAt,f={atMs:Number.isFinite(g)?Math.max(0,Math.round(g)):0,cc:u,level:p,budgetMs:Number.isFinite(t)&&t>=0?t:null,reason:n,matchingHave:typeof s=="boolean"?s:null,budgetGeometry:{...i}};if(o&&(f.projection={...o}),l===!0&&(f.trial=!0),a){try{Object.assign(f,this.#Fe(a))}catch{Object.assign(f,{holders:null,haveHolders:null,staleHolders:null,heldMissHolders:null})}a.row=f}this.peerEligibilityCounters[n]=Ve(this.peerEligibilityCounters[n]),this.peerEligibilityRecords.length===64&&(this.peerEligibilityRecords.shift(),this.peerEligibilityDropped=Ve(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,n){let s=this.#v(t);!e.has(s)&&e.size>=16&&e.delete(e.keys().next().value);let i=e.get(s)||[];Ke(i,n),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}}#We(e,t,n,s){if(!(t>0)||!Number.isFinite(t)||nWi&&o.firstBytes.shift();let l=s-n;l>=Ki&&i>=Kr&&(o.flows.push({value:Math.min(1e6,i/l),flowMs:l,at:a}),o.flows.length>Wi&&o.flows.shift())}#pe(e,t,n=null){if(!e||e.closed||!Number.isSafeInteger(t)||t<=0)return;let s=this.#oe(e);Number.isFinite(n)&&(s.flows=s.flows.filter(i=>i.at>=n)),s.usefulAt=I()}#Ve(e,t,n){let s=this.#oe(e),i=I();s.firstBytes=s.firstBytes.filter(u=>i-u.at<=Wr),s.flows=s.flows.filter(u=>i-u.at<=Wr);let o=s.firstBytes.reduce((u,p)=>u===null?p.value:(u+p.value)/2,null),a=s.flows.filter(u=>u.flowMs>=(o??0)*3),l=cl((a.length>=2?a:s.flows).map(u=>u.value),.75),c=l!==null&&(o??0)+n/l<=t,h=l===null&&(o??0)=sl)return{state:s,firstByteMs:null,rate:null,refresh:!0};if(l===null)return null}return{state:s,firstByteMs:o,rate:l,refresh:!1}}#$e(e,t){let n=_e(this.renditionOriginSamples.get(t)||[],.5);if(n===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,n-(s===null?0:Date.now()-s))}#ge(e,t,n){let s=n.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>=hl?"stretch":o>s*1.25?"late":"stretch"}#me(e,t,n){let s=e==="fits"?I()+t*1.25+100:e==="stretch"?n.limit:null;s!==null&&n.extend(s)&&(this.counters.peerWaitExtended+=1)}#J(e,t,n,s){let i=a=>Number.isFinite(a)?Math.round(a):null,o=this.peerSelection.rate();return{stage:e,transferMs:i(t),holderWaitMs:i(n),roomMs:i(s.limit-I()),firstByteMs:i(this.peerSelection.firstByteMs()),rateBytesPerSecond:Number.isFinite(o)?Math.round(o*1e3):null}}#ye(e,t){for(let n of this.links.values())if(!(!this.#N(n)||this.banned.has(n.pubkey)||!n.have.has(e))&&this.peerSelection.summary(n).attempts===0&&!(t&&this.discovery.stale(t,n.pubkey)))return n;return null}#be(e,t){return t.limit-I()>(this.peerSelection.firstByteMs()??0)&&!!this.#ye(e.key,e.context)}async#ae(e,t,n,s,i){let o=this.options.traceRequests?this.#d(e):null,a=n.deadline;if(this.options.transferWorkerUrl!==void 0&&this.transferWorkerState!=="ready")return null;let l=this.discovery.contexts.get(e.frag.type||"main"),c=n.knownKey??await this.#R(e);if(t.aborted||this.stopped||n.currentValid&&!n.currentValid())return this.#E(e,s,"aborted-before-eligibility",null,i,void 0,void 0,!1,o),null;if(n.cachedOnly){let N=x=>[...n.cachedOnly].filter(([A,v])=>(!x||v.has(c))&&A.have.has(c)&&this.links.get(A.pubkey)===A&&this.#K(A,e)&&!this.banned.has(A.pubkey)&&A.supportsRanges===!0&&(this.remoteFraming.get(A.pubkey)??1)>=2).map(([A])=>A),d=N(!0);if(!d.length&&n.lateHaveRace){for(d=N(!1);!d.length&&!t.aborted&&!this.stopped&&I()0}if(t.aborted||this.stopped||I()>=n.limit||(n.cachedHolders=new Set(d),!n.cachedHolders.size||!this.#L()))return null;this.counters.zeroBudgetPeerRaces+=1}let h=this.#v(e),u=l?.rendition===h&&this.discovery.contexts.get(l.mediaType)===l?l:null;if(u&&!n.cachedOnly){this.discovery.demand(l.mediaType,h,c);let N=this.discovery.counters.checks;this.#te();try{this.#je(u,N)}catch{}}let p={key:c,rendition:h,context:u,recorded:!1,asked:new Set,row:null},g=![...this.links.values()].some(N=>N.have.has(c));if(g&&!this.#I(c,h,e))return this.#E(e,s,"no-have-no-wait",!1,i,void 0,p,!1,o),null;let f=this.renditionSizes.get(h),m=g?this.#$e(c,h):0,y=f?this.peerSelection.projectMs(f):null,w=!g&&this.#L()&&[...this.links.values()].some(N=>this.#K(N,e)&&N.supportsRanges===!0&&N.have.has(c)&&!this.banned.has(N.pubkey)&&(this.remoteFraming.get(N.pubkey)??1)>=2&&!(u&&this.discovery.stale(u,N.pubkey))),b=n.cachedOnly||w?"unknown":this.#ge(y,m,n),M=null;if(b==="late"&&!g&&this.#be(p,n)&&(M=this.#J("entry",y,m,n),b="stretch"),b==="late")return this.#E(e,s,"projected-late",!g,i,this.#J("entry",y,m,n),p,!1,o),this.#C(p,{everyServing:!0}),this.counters.peerProjectedLate+=1,null;this.#me(b,m+y,n),g&&(this.#E(e,s,"no-have-wait",!1,i,void 0,p,!1,o),this.counters.coordinatedWaits+=1);let R=n.deadline-I();if(t.aborted||this.stopped||R<=0)return null;this.counters.commitmentRequests+=1;let Z=at(N=>{if(t.aborted||this.stopped||I()>=n.deadline)throw new Error("Commitment load no longer active.");return this.options.getCommitment(e,{signal:N})},t,R).then(N=>({ok:!0,event:N}),()=>({ok:!1}));if(g){for(;!t.aborted&&!this.stopped&&I()d.have.has(c));){if(!this.#I(c,h,e))return this.#E(e,s,"wait-no-longer-eligible",!1,i,void 0,p,!1,o),null;await this.#Q(c,Math.min(100,n.deadline-I()),t)}let N=t.aborted||this.stopped;if(N||I()>=n.deadline)return this.#E(e,s,N?"wait-aborted":"wait-expired",null,i,void 0,p,!1,o),(!N||n.expired&&!this.stopped)&&this.#C(p,{everyServing:!0}),null}this.#E(e,s,g||n.lateHaveMatched?"have-after-wait":"have-at-entry",!0,i,M??void 0,p,M!==null,o);let k,C;try{let N=await Z;if(!N.ok)throw new Error("Commitment unavailable.");C=N.event,k=this.#ce(N.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(!k)return this.counters.commitmentRejected+=1,null;if(n.currentValid&&!n.currentValid()||(n.revalidateAuthority===!0&&(n.revalidateAuthority=()=>!!this.#ce(C,{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)||n.cachedOnly&&k.v!==3)return null;if(!this.renditionSizes.has(h)&&this.renditionSizes.size>=16&&this.renditionSizes.delete(this.renditionSizes.keys().next().value),this.renditionSizes.set(h,k.size),k.v===3&&this.options.multiHolder){let N=await this.#Ze(e,t,n,c,k,l,o);if(N!==void 0)return N&&g&&(this.counters.coordinatedPeerLoads+=1),N&&{...N,holderContext:u}}if(n.cachedOnly)return null;let U=this.peerSelection.projectMs(k.size),_=this.#ge(U,0,n);if(_==="late"&&!g&&(M!==null||this.#be(p,n))&&(M=this.#J("commitment",U,0,n),_="stretch",p.row&&(p.row.projection={...M},p.row.trial=!0)),_==="late")return this.#E(e,s,"projected-late",!0,i,this.#J("commitment",U,0,n),p,!1,o),this.counters.peerProjectedLate+=1,null;this.#me(_,U,n);let z=new Set;for(;!t.aborted&&!this.stopped&&I()N||(d??0)>N)return this.counters.peerSkippedLate+=1,null;let x=(V,ne)=>this.peerSelection.estimate(V,k.size)===null||this.peerSelection.estimate(V,k.size)*1.25+25<=ne,A=M&&z.size===0?this.#ye(c,p.context):null;A&&this.peerSelection.markSelected(A);let v=A??this.peerSelection.select([...this.links.values()].filter(V=>this.#N(V)),c,z,k.size,N);if(!v){if(![...this.links.values()].some(V=>!V.closed&&!z.has(V.pubkey)&&V.have.has(c)&&x(V,N)))return this.counters.peerNoFit+=1,this.#C(p,{unfit:[...this.links.values()].filter(V=>!V.closed&&!z.has(V.pubkey)&&V.have.has(c)&&!x(V,N)).map(V=>V.pubkey)}),null;await this.#Q(c,Math.min(100,n.deadline-I()),t);continue}z.add(v.pubkey),p.asked.add(v.pubkey),A&&(this.counters.peerUntestedTrial+=1);let B=this.peerSelection.estimate(v,k.size);B!==null&&n.extend(I()+B*1.25+25)&&(this.counters.peerWaitExtended+=1);let O=I(),P=n.deadline-I(),T=[...this.links.values()].filter(V=>this.#N(V)&&!z.has(V.pubkey)&&V.have.has(c)&&x(V,P)).length,D=P-Math.min(2,T)*25,H=B===null?Math.min(P,Math.max(25,D)):Math.min(P,Math.max(25,P/Math.min(3,T+1),B*1.25+25)),F=this.#Xe(t,O,k.size,n,d),ee;try{ee=await v.request(c,Math.max(1,H),{signal:F.signal,expectedSize:k.size,onProgress:F.progress,onResult:V=>this.#we(e,v,P,V,null,o)})}finally{F.done()}if(this.peerSelection.observe(F.observation()),F.abandoned)return this.#T(v,I()-O),this.counters.peerAbandoned+=1,this.#C(p),null;if(!ee||t.aborted||this.stopped){!t.aborted&&!this.stopped&&this.#T(v,I()-O);continue}let j=await Nt(ee);if(this.stopped)return null;if(ee.byteLength!==k.size||j!==k.sha256){if(this.#T(v,I()-O),this.counters.peerCorrupt+=1,this.banned.add(v.pubkey),p.asked.delete(v.pubkey),v.close("integrity"),t.aborted)return n.expired&&this.#C(p),null;continue}return t.aborted?(n.expired&&this.#C(p),null):k.expiresAt<=Math.floor(Date.now()/1e3)?null:(this.#T(v,I()-O,ee.byteLength),g&&(this.counters.coordinatedPeerLoads+=1),A&&(this.counters.peerUntestedTrialLoaded+=1),{key:c,bytes:ee,discoveryContext:l,holderContext:u,pubkey:v.pubkey,demand:p,connection:v.pc})}return!this.stopped&&(!t.aborted||n.expired)&&this.#C(p),null}#Ge(e){let t=this.transferIds.get(e);return t===void 0&&(t=this.nextTransferId++,this.transferIds.set(e,t)),t}#N(e){return!e.closed&&!e.busy&&!this.peerLeases.has(e)}#K(e,t){return this.#N(e)||!!(t?.[Te]&&!e.closed&&this.peerLeases.has(e))}#Ye(e,t,n){return this.peerAdmission.waited++,new Promise(s=>{let i,o=c=>{this.peerLeaseWaiters.delete(l)&&(clearTimeout(i),this.timers.delete(i),n.removeEventListener("abort",a),this.peerAdmission[c]++,s(c==="granted"))},a=()=>o("cancelled"),l=()=>{if(this.stopped||n.aborted)return a();if(I()>=t)return o("expired");e.some(c=>this.links.get(c.pubkey)===c&&this.#N(c))&&o("granted")};this.peerLeaseWaiters.add(l),n.addEventListener("abort",a,{once:!0}),i=setTimeout(()=>o("expired"),Math.max(0,t-I())),this.timers.add(i),l()})}async#Ze(e,t,n,s,i,o,a){if(n.currentValid&&!n.currentValid())return null;let l=this.options.transferWorkerUrl!==void 0;if(l&&(!this.#L()||this.transferWorkerState!=="ready"))return null;if(!this.#L()||!Array.isArray(i.pieces))return;let c=ll(e.url);if(!n.peerOnly&&this.originsWithoutRanges.has(c))return l?null:void 0;let h=b=>this.links.get(b.pubkey)===b&&!b.closed&&b.supportsRanges===!0&&b.have.has(s)&&!this.banned.has(b.pubkey)&&(this.remoteFraming.get(b.pubkey)??1)>=2&&(!n.cachedHolders||n.cachedHolders.has(b)),u=[...this.links.values()].filter(b=>h(b)&&this.#K(b,e)),p=()=>u.filter(b=>h(b)&&this.#N(b)),g=p();if(!g.length&&e?.[Te]&&u.some(b=>this.peerLeases.has(b))&&(await this.#Ye(u,n.limit,t),g=p()),this.stopped||t.aborted||I()>=n.limit||typeof n.revalidateAuthority=="function"&&!n.revalidateAuthority())return null;if(!g.length)return l?null:void 0;let f=new Map(g.map(b=>[b,this.#Ve(b,Math.max(0,n.limit-I()),i.pieceSize)]).filter(([,b])=>b!==null));if(!f.size)return this.counters.peerNoFit+=1,null;let m=[...f.keys()],y={};for(let b of m)this.peerLeases.set(b,y);this.peerAdmission.claims+=m.length;let w=()=>{t.removeEventListener("abort",w);for(let b of m)this.peerLeases.get(b)===y&&this.peerLeases.delete(b);for(let b of[...this.peerLeaseWaiters])this.#h(0,b);this.latePeerOwners.size&&this.#h(0,()=>this.#A())};t.addEventListener("abort",w,{once:!0});try{let b=new Map(m.map(v=>[this.#Ge(v),v])),M=Math.floor(n.limit),R=n.peerOnly?n.limit:n.limit+n.originReserveMs,Z={size:i.size,sha256:i.sha256,pieces:i.pieces,deadline:M,maxHolders:this.options.maxHoldersPerObject,originReserveMs:0,...n.peerOnly?{peerOnly:!0}:{}},k;try{k=l?await this.transferWorker.transfer(Z,{signal:t}):this.core.transfer(Z)}catch{return null}if(this.stopped||t.aborted||l&&I()>=M||n.currentValid&&!n.currentValid()||typeof n.revalidateAuthority=="function"&&!n.revalidateAuthority()||m.some(v=>!h(v)||v.busy||this.peerLeases.get(v)!==y))return k?.free(),null;if(!k)return l||n.peerOnly?null:void 0;this.multiHolder.transfers+=1;let C=a,U=this.traceBase,_=(v,B,O)=>{let P=Math.floor(I()),T=H=>(this.options.traceRequests&&this.#e({k:"xfer",load:C,op:v,at:P-U,...B,out:H&&{c:H.commands.map(({t:F,peer:ee,p:j})=>({t:F,...ee!==void 0?{peer:ee}:{},...j?{p:[...j]}:{}})),next:H.next===null?null:H.next-U,late:H.late,finished:H.finished}}),H),D=O(P);return D?.then?D.then(T):T(D)};n.extend(n.limit);let z=i.pieceSize,N=({start:v,end:B})=>[v*z,Math.min(B*z,i.size)],d=[...b].map(([v,B])=>[v,f.get(B).firstByteMs,f.get(B).rate]),x=n.peerOnly?null:_e(this.#W(e),.5),A=n.peerOnly?null:[0,x?i.size/x:null];return await new Promise(v=>{let B=new Map,O=new Set,P=new WeakSet,T=new Map,D=new Map,H=!1,F=null,ee=null,j=null,V=0,ne=0,ae=(W,ve)=>{let ie=W?.verified==null?0:Math.max(0,W.verified-ne);return W?.verified!=null&&(ne=Math.max(ne,W.verified)),this.multiHolder.unusedBytes+=ve-ie,ie},ge=I(),re=0,pe=0,Q=W=>(W!==null&&(clearTimeout(W),this.timers.delete(W)),null),me=W=>{if(!H){H=!0,F=Q(F),ee=Q(ee);for(let ve of[...B.values(),...O])ve.abort();j?.(),n.onDeadline=null,t.removeEventListener("abort",et),k.free(),v(W)}},et=()=>me(null);t.addEventListener("abort",et,{once:!0});let Ie=(W,ve,ie,Be=ft)=>{if(H)return;let S=E=>{if(!H){if(n.currentValid&&!n.currentValid()||(l||n.peerOnly)&&I()>=R)return me(null);E?Be(E):me(null)}};try{let E=_(W,ve,ie);E?.then?E.then(S,()=>me(null)):S(E)}catch{me(null)}},Wn=(W,ve)=>{if(W.t==="request"){let ie=b.get(W.peer),Be=new AbortController;B.set(W.peer,Be);let[S,E]=N(W.range),q=I(),Y=Math.max(1,M-q),L=null,K=-1/0;pe+=1,f.get(ie).refresh&&(f.get(ie).refreshStartedAt??=I(),f.get(ie).state.probeAt=I());let J=X=>{let $=I();H||B.get(W.peer)!==Be||$-Kk.progress(te,W.peer,X)))};ie.request(s,Y,{signal:Be.signal,expectedSize:E-S,onProgress:J,range:{start:W.range.start,end:W.range.end,objectSize:i.size},onResult:X=>{L=X,this.#we(e,ie,Y,X,W.range,a)}}).then(X=>{B.get(W.peer)===Be&&B.delete(W.peer),re=Math.max(re,I()-q),!H&&(L?.firstByteMs!==null&&L?.elapsedMs!==null&&L?.receivedBytes&&this.peerSelection.observe({firstByteMs:L.firstByteMs,bytes:L.receivedBytes,flowMs:L.elapsedMs-L.firstByteMs}),X?(this.#T(ie,I()-q,X.byteLength),Ie("delivered",{source:W.peer,p:[W.range.start,W.range.end],bytes:X.byteLength},$=>k.delivered($,W.peer,W.range,X),$=>{let te=ae($,X.byteLength);this.multiHolder.peerBytes+=te,te>0&&T.set(ie.pc,(T.get(ie.pc)??0)+te);let xe=L?.elapsedMs-L?.firstByteMs;te>0&&f.get(ie).refresh&&L?.receivedBytes>=Kr&&Number.isFinite(xe)&&xe>=0&&xek.failed($,W.peer))))},()=>{H||Ie("failed",{source:W.peer},X=>k.failed(X,W.peer))})}else if(W.t==="origin"){if(n.peerOnly){this.multiHolder.failed+=1,me(null);return}j??=this.#Z(s);let ie=new AbortController,[Be,S]=N(W.range),E=I(),q=null,Y=K=>{q=K,this.originRangeOutcomes[K.outcome]=Ve(this.originRangeOutcomes[K.outcome])};O.add(ie),this.multiHolder.originRanges+=1;let L=()=>{this.originsWithoutRanges.has(c)||(this.originsWithoutRanges.add(c),this.multiHolder.originRangesIgnored+=1)};(n.origin?.Loader?Ui(n.origin,e,Be,S,{signal:ie.signal,onIgnored:L,onResult:Y}):zi(e,Be,S,{signal:ie.signal,onIgnored:L,onResult:Y})).then(K=>{if(O.delete(ie),this.options.traceRequests&&this.#e({k:"origin",load:C,at:this.#s(E),ms:Math.round(I()-E),ranged:!0,range:[W.range.start,W.range.end],outcome:q?.outcome??(K?"payload":H?"abort":"none"),httpStatus:q?.httpStatus??null,bytes:K?.byteLength??null}),H)return;let J=[W.range.start,W.range.end];if(!K)return Ie("failed",{source:"origin"},X=>k.failed(X,"origin"));this.#We(e,I()-E,K.byteLength,i.size),this.counters.bytesFromOrigin+=K.byteLength,Ie("delivered",{source:"origin",p:J,bytes:K.byteLength},X=>k.delivered(X,"origin",W.range,K),X=>{let $=ae(X,K.byteLength);this.multiHolder.originBytes+=$,V+=$,ft(X)})})}else if(W.t==="cancel"||W.t==="abandon"){let ie=B.get(W.peer);W.t==="abandon"&&(this.multiHolder.abandoned+=1,ie&&P.add(ie)),ie?.abort(W.t==="abandon"?ot.ABANDON_REASON:void 0)}else if(W.t==="ban"){let ie=b.get(W.peer);this.multiHolder.bans+=1,this.counters.peerCorrupt+=1,this.banned.add(ie.pubkey),ie.close("integrity")}else if(W.t==="deliver"){this.multiHolder.delivered+=1,this.multiHolderTimings.push([I()-ge,re,pe]),this.multiHolderTimings.length>128&&this.multiHolderTimings.shift();let ie=ve.bytes.byteOffset===0&&ve.bytes.byteLength===ve.bytes.buffer.byteLength?ve.bytes:ve.bytes.slice();me(i.expiresAt<=Math.floor(Date.now()/1e3)?null:{key:s,bytes:ie,discoveryContext:o,multi:!0,peerBytes:Math.max(0,i.size-V),contributions:[...T].map(([Be,S])=>({connection:Be,bytes:S})),shortRefreshes:[...D].map(([Be,S])=>({connection:Be,at:S}))})}else W.t==="fail"&&(this.multiHolder.failed+=1,me(null))},ft=W=>{if(!H){if(!W)return me(null);for(let ve of W.commands)if(Wn(ve,W),H)return;F=Q(F),W.next!==null&&(F=this.#h(Math.max(0,W.next-I()),()=>{F=null,Ie("tick",{},ve=>k.tick(ve))}))}};n.onDeadline=()=>H?!1:(Ie("tick",{},W=>k.tick(W)),!H&&ee===null&&(ee=this.#h(Math.max(0,n.limit+n.originReserveMs-I()),()=>{ee=null,me(null)})),!0);let St=[...f.values()].some(W=>W.refresh||W.firstByteMs===null)?null:this.peerSelection.firstByteMs(),rn=[...b].filter(([,W])=>f.get(W).rate===null).map(([W])=>W),sn={peers:d,origin:A,sharedFirstByteMs:St,sharedRate:this.peerSelection.rate(),probePeers:rn};Ie("start",this.options.traceRequests?{size:i.size,pieces:i.pieces.length,pieceSize:z,deadline:M-U,maxHolders:this.options.maxHoldersPerObject,originReserveMs:0,...n.peerOnly?{peerOnly:!0}:{},...structuredClone(sn),holders:[...b].map(([W,ve])=>[W,this.#D(ve.pubkey)])}:null,W=>k.start(W,sn),W=>{W?.late&&(this.multiHolder.late+=1),ft(W)})})}finally{w()}}#Xe(e,t,n,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(),h=null,u={abandoned:!1,signal:o.signal},p=()=>{u.abandoned||o.signal.aborted||(u.abandoned=!0,o.abort(ot.ABANDON_REASON))},g=null;if(i!==null){let m=c?s.deadline-n/c:-1/0;g=setTimeout(()=>{h===null&&p()},Math.max(ul,i*3,m-I()))}let f=m=>{let y=l.at(-1);if(!y)return null;let w=l[0];for(let b of l)if(b[0]<=y[0]-m)w=b;else break;return y[0]-w[0]>=150?{bytes:y[1]-w[1],ms:y[0]-w[0]}:null};return u.progress=(m,y,w)=>{let b=I();if(h===null&&(h=Number.isFinite(w)?w:b-t),l.push([b,m]),l.length>256&&l.shift(),b-ts.deadline)&&p()},u.observation=()=>{let m=l.length?l.at(-1)[0]-l[0][0]:0,y=f(Math.max(300,m/2));return{firstByteMs:h,bytes:y?.bytes??0,flowMs:y?.ms??0,totalFlowMs:m}},u.done=()=>{clearTimeout(g),e.removeEventListener("abort",a)},u}#T(e,t,n){this.peerSelection.record(e,t,n),e.closed&&this.peerSelection.forget(e)}#we(e,t,n,s,i=null,o=null){try{if(!Zi.includes(s.outcome))return;this.#Ke(t,s);let a=p=>Number.isFinite(p)&&p>=0?p:null,l=p=>Number.isSafeInteger(p)&&p>=0?p:null,c=null,h=null;try{c=l(e?.frag?.cc)}catch{}try{h=l(e?.frag?.level)}catch{}let u={atMs:Math.max(0,Math.round(I()-this.transportStartedAt)),id:this.transportConnections.get(t.pc)?.id||0,holder:this.#D(t.pubkey),cc:c,level:h,remainingMs:a(n),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:jn["link-close"].includes(s.closeReason)?s.closeReason:null};this.peerRequestCounters[s.outcome]=Ve(this.peerRequestCounters[s.outcome]),this.peerRequestRecords.length===64&&(this.peerRequestRecords.shift(),this.peerRequestDropped=Ve(this.peerRequestDropped)),this.peerRequestRecords.push(u),this.#e({k:"request",load:o,at:this.#s(),range:i?[i.start,i.end]:null,...u})}catch{}}#Je(e){let t=this;class n{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.#Qe(i);if(this.race=l,!l)return this.inner.load(i,o,a);let c=[],h=0,u=l.sampled||t.#xe(),p={...a,onProgress:a.onProgress?(g,f,m,y)=>{try{m?.byteLength&&(u&&c.push(m.slice(0)),h+=m.byteLength)}catch{}a.onProgress(g,f,m,y)}:void 0,onSuccess:(g,f,m,y)=>{let w=Fn(f),b=null,M=0;try{let R=g?.data;R?.byteLength?(u&&(b=R.slice(0)),M=R.byteLength):h&&(u&&(b=n.join(c)),M=h)}catch{b=null,M=0}l.originSucceeded=!0,a.onSuccess(g,f,m,y),t.#M(y,w),M?t.#n("origin-loaded",()=>t.#tt(l,b,M)):t.#n("origin-empty",()=>t.#U(l))},onError:(...g)=>{t.#n("origin-error",()=>t.#U(l)),a.onError(...g)},onTimeout:(...g)=>{t.#n("origin-timeout",()=>t.#U(l)),a.onTimeout(...g)}};return a.onAbort&&(p.onAbort=(...g)=>{t.#n("origin-abort",()=>t.#U(l)),a.onAbort(...g)}),this.inner.load(i,o,p)}abort(){return this.race&&t.#U(this.race),this.inner.abort()}destroy(){return this.race&&!this.race.originSucceeded&&!this.race.originDone&&t.#U(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,h)=>c+h.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 n}#Qe(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 n=e.url||t.url,s=(this.options.segmentKey||Gi)(n,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.#et(o)),o}catch(t){return this.#o("begin-race",t),null}}async#et(e){if(e.keyPromise=Nt($i.encode(e.keyText)),e.key=await e.keyPromise,this.stopped)return;if(!e.sampled||!this.options.serveOnCellular&&Pt())return e.peerDone=!0,e.skipPeers=!0,this.#n("settle",()=>this.#ee(e));let t=e.t0+this.options.lateWindowMs,n=new Set,s=e.peersAtStart>0;for(;!this.stopped&&!e.settled&&!e.originFailed&&I()0,this.#n("settle",()=>this.#ee(e))}#Q(e,t,n){return new Promise(s=>{let i=null,o=l=>{l&&!l.includes(e)||(clearTimeout(i),n?.removeEventListener("abort",a),this.haveWaiters.delete(o),s())},a=()=>o();if(n?.aborted)return s();n?.addEventListener("abort",a,{once:!0}),i=setTimeout(o,Math.max(0,Math.min(t,1e3))),this.haveWaiters.add(o)})}async#tt(e,t,n){if(this.stopped||e.originFailed)return;let s=t&&new Uint8Array(t),i=I();this.counters.originLoaded+=1,this.counters.bytesFromOrigin+=n,e.originBytes=n,Ke(this.originLatencySamples,i-e.t0),e.sampled&&(e.originDigest=await Nt(s)),e.originDone=!0,await e.keyPromise,!this.stopped&&(s&&this.#z(e.key,s),this.#n("settle",()=>this.#ee(e)))}#U(e){e.settled||e.originDone||(e.controller.abort(),e.originDone=!0,e.originFailed=!0,this.#n("settle",()=>this.#ee(e)))}async#ee(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 Nt(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),Ke(this.peerLatencySamples,s),t.bytesFromPeers+=e.peerBytes.byteLength,s<=this.options.originFallbackMs?(t.peerInTime+=1,t.peerInTimeBytes+=e.peerBytes.byteLength):t.peerLate+=1}#z(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 n=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]:[],n)}#nt(e){let t=this.held.get(e);if(t){this.held.delete(e),this.heldBytes-=t.byteLength,this.warmAhead?.release(e);for(let n of this.links.values())n.sendHaveChange([],[e])}}#ve(e,t=!0){let n=[];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),n.push(i)}if(t&&n.length)for(let s of this.links.values())s.sendHaveChange([],n);return n}#xe(){return!this.stopped&&!this.disabledReason&&this.options.serve===!0}#p(){return!this.stopped&&!this.disabledReason&&this.options.serve===!0&&this.#P()!==0&&(this.options.serveOnCellular||!Pt())}#P(){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#rt(e,t,n=null){if(this.uploadPacer)return this.#st(e,t,n);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(n){let h=xt(i.byteLength),u=n.start*h,p=Math.min(n.end*h,i.byteLength);if(!(ua)return this.#y("session-allowance"),null;let l=[...this.links.values()].filter(h=>h!==e&&(h.outboundInFlight>0||Date.now()-h.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:u}),this.lifecycle.signal,this.options.admissionTimeoutMs)===!0}catch{this.#o("upload-reservation")}if(!h||this.stopped||e.closed||this.options.serve!==!0||!this.options.serveOnCellular&&Pt())return h||(this.uploadQuotaBytes-=o),this.#y(h?"reservation-inactive":"reservation-refused"),null}if(this.counters.bytesUploaded+=o,this.counters.uploadsServed+=1,this.options.testHooks?.corruptUploads){let h=i.slice();return h[h.length>>1]^=255,h}return i}#y(e){this.counters.uploadsRefused+=1,this.uploadRefusalCounters[e]=Ve(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 n=this.held.get(e)?.byteLength;if(!Number.isSafeInteger(n)||n<1)return null;if(!t)return{key:e,size:n,charge:n,range:null};let s=xt(n);if(!Number.isSafeInteger(t.start)||!Number.isSafeInteger(t.end)||t.start<0||t.end<=t.start||t.end>Math.ceil(n/s))return null;let i=Math.min(t.end*s,n)-t.start*s;return{key:e,size:n,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&&Pt()||this.banned.has(e.link.pubkey))return!1;let n=this.#Ae(e.key,e.range);if(!n||n.size!==e.size||n.charge!==e.charge)return!1;let s=this.#P();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(!h())return null;let u=this.admissionChecks.get(e.pubkey)?.ticket??this.admitted.get(e.pubkey)?.ticket;if(this.options.admit&&!await at(()=>this.#x(e.pubkey,u,"upload"),c,this.options.admissionTimeoutMs))return this.#y("admission"),e.close("admission"),null;if(!h())return null;if(this.uploadQuotaBytes+=i.charge,o=!0,this.options.reserveUploadBytes){try{a=await at(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(!h()||this.options.admit&&this.admitted.get(e.pubkey)?.ticket!==u)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.#P()===0&&this.#Se(),this.uploadPacer.finish(i,l)}}async#it(){this.coreState="loading";try{let e=await Ni(this.options.coreWasm,{onFailure:n=>this.#le(n)});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.#ot(e)}catch(e){this.coreState="failed",this.options.transferWorkerUrl!==void 0&&(this.transferWorkerState="failed",this.transferWorkerReason="core-failed"),this.#o("core",e)}}async#ot(e){this.transferWorkerState="loading";try{let t=this.options.WorkerImpl,n=await Hi({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){n.stop();return}this.transferWorker=n,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.#L();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()}#L(){return this.options.multiHolder===!0&&this.options.mode==="peer-first"&&!!this.core&&!this.core.retired&&this.coreLinks.js===0}#at(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 ot(e)}#ce(e,t){if(this.coreVerifier)try{let n=this.coreVerifier.verifySegmentCommitment(e,t);return this.coreDecided.wasm+=1,n}catch(n){this.#le(n)}return this.coreDecided.js+=1,Mi(e,t)}async#lt(){let e=this.options.secretKey||Vt();if(this.pool=new On(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 In({pool:this.pool,swarmId:this.options.swarmId,secretKey:e,maxEventAgeSeconds:60}),this.session.onPresence(t=>this.#n("presence",()=>this.#gt(t))),this.session.onSignal(t=>this.#n("signal",()=>this.#mt(t))),this.session.onError(t=>this.#o("session",t)),this.session.start(),this.#V(),this.#k(this.options.presenceIntervalMs,.3,()=>this.#V())}#V(){if(!(!this.session||this.stopped))try{this.session.announcePresence({role:"viewer",transports:[{type:qn,publicKey:this.session.pubkey,...this.#L()?{obj:2}:{}}],have:this.#p()?[...this.held.keys()].slice(-8):[],open:this.#ht(),...this.#re()?{ticket:this.#re()}:{}}),this.counters.presenceSent+=1;for(let[e,t]of this.renditions){if(t{this.reannounceTimer=null,this.#V()})}#q(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.#q(t,e.rendition)||e.keys.some(n=>t.have.has(n))))}#Re(e){let t=[...this.links.values()].filter(n=>this.#q(n,e.rendition));return t.length>0&&t.every(n=>this.discovery.stale(e,n.pubkey))}#ct(e){return[...this.links.values()].filter(t=>this.#q(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.#H(e.pubkey)&&(!this.#G()||we(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()-n.activityAt<3e4);return Qi([...this.links.values()].filter(n=>!t.some(s=>!this.discovery.stale(s,n.pubkey)&&(this.#q(n,s.rendition)||s.keys.some(i=>n.have.has(i))))),{...this.options,banned:this.banned,tier:n=>this.#Ie(n)})}#F(e=this.discovery.window,t=!0){if(!e||!this.discovery.end(e))return;clearTimeout(e.timer),this.timers.delete(e.timer);let n=e.attempt,s=n?.dial;t&&s&&s.discovery===n&&s.negotiation===n.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.#F(t))}#te(){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.#ct(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 n=this.discovery.begin(t);if(!n)return;this.#Re(t.context)&&this.discovery.counters.staleHolder++;let s=n.window;s.timer||(s.timer=this.#h(Math.max(0,s.expiresAt-Date.now()),()=>this.#F(s))),this.#n("discovery",()=>this.#ie(n.pubkey,n))}#$(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,n])=>n.open&&n.at>=e&&!this.banned.has(t)).sort((t,n)=>n[1].at-t[1].at).map(([t])=>t)}#Oe(){return Qi(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(),n=2*this.options.presenceIntervalMs;for(let[s,i]of e.announced??[]){if(t-i>n)continue;let o=this.renditions.get(s);if(o!==void 0&&t-o<=3e4)return 2}return 0}#Ce(e,t,n){let s=["Unhelpful","Serving","Consumer"][t];e[`${n}${s}`]++}#ht(){return this.#j(),this.discovery.reserved()?!1:this.#_()||this.links.size>=2&&!!this.#Oe()}#ut(e,t){if(this.discovery.reserved())return null;let n=Number.isSafeInteger(e)&&e>0&&typeof t=="string"&&/^[0-9a-f]{64}$/u.test(t)&&this.held.has(t)&&this.#p();if(e!==0&&!n||this.links.size<2||Date.now()-this.lastEvictionAts!==e).slice(0,this.options.maxReferrals);return n.length&&(this.counters.referralsSent+=n.length),{retryAfterMs:t,referrals:n}}#ue(e,t,n,s={}){try{return this.stopped?!1:(this.session.sendSignal(e,{type:t,transport:qn,requestId:n,payload:s}),this.counters.signalsSent+=1,!0)}catch(i){return this.counters.publishErrors+=1,this.#o("signal-send",i),!1}}#ft(e){return yl(e,this.options)}#pt(e,{retryAfterMs:t,referrals:n}){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.#te();return}if(!(this.links.has(e)||this.dials.has(e)||this.banned.has(e)||!this.#_()))return this.cooldowns.delete(e),this.#ie(e)}));for(let i of n)if(i!==this.session?.pubkey&&!(this.#G()&&!this.admitted.has(i))&&!(this.links.has(i)||this.dials.has(i)||this.#H(i)||!this.#_())){if([...this.dials.values()].filter(o=>o.outgoing).length>=this.options.maxDialsInFlight)break;this.counters.referralsFollowed+=1,this.#n("referral",()=>this.#ie(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"}#re(){return we(this.options.ticket)?this.options.ticket:void 0}async#x(e,t,n="other"){if(this.stopped)return!1;if(!this.#G())return!0;if(!we(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 at(a=>{try{let l=Xi.includes(n)?n:"other";this.admissionCallCounters[l]=Ve(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,...we(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}async#gt({from:e,payload:t}){if(this.stopped||t.role!=="viewer")return;let n=t.transports.find(l=>l.type===qn);if(!n)return;this.remoteFraming.delete(e),this.remoteFraming.set(e,n.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.#te());let s=this.links.has(e)||this.dials.has(e),i=this.admitted.get(e);i&&we(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.#A();return}if(!s&&(this.#H(e)||!this.#_()||!this.#ne())){o&&t.open!==null&&this.#$(e,t.open);return}let a=this.admissionChecks.get(e);if(s&&a){we(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.#A(),!(this.links.has(e)||this.dials.has(e)||this.#H(e)||!this.#_())&&this.#h(Math.random()*1500,()=>{if(!(this.links.has(e)||this.dials.has(e)||this.#H(e)||!this.#_())&&this.#ne())return this.#ie(e)}))}#g(e,t,n,s){try{if(!jn[t]?.includes(n))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:n};Number.isSafeInteger(s)&&s>=0&&s<=256&&(a.candidates=s,a.candidatesCapped=s===256),this.transportCounters[t][n]=Ve(this.transportCounters[t][n]),this.transportRecords.length===64&&(this.transportRecords.shift(),this.transportDropped=Ve(this.transportDropped)),this.transportRecords.push(a)}catch{}}#Ne(e,t,n){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}`,n,s)}catch{this.#g(e,`local-${t}`,n)}}#de(e,t,n){this.#g(e,t,n);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}}#Pe(e){let t=this.options.RTCPeerConnectionImpl||globalThis.RTCPeerConnection,n=new t({iceServers:this.options.iceServers,iceTransportPolicy:this.options.iceTransportPolicy}),s={id:this.transportSequence{try{let c=n[o];this.#g(n,i,jn[i].includes(c)?c:"unknown")}catch{this.#g(n,i,"unknown")}};try{n.addEventListener(a,l),s.listeners.push([a,l]),l()}catch{}}return n}#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))}#se(e,t=!0){let n=e.negotiation;if(n&&(n.controller.abort(),n.onDataChannel&&e.pc.removeEventListener("datachannel",n.onDataChannel),n.channel&&n.onOpen&&n.channel.removeEventListener("open",n.onOpen),t))try{n.channel?.close()}catch{}}#He(e,t,n){!n&&e.discovery&&(this.#F(e.discovery.window,!1),e.discovery=null),e.negotiation&&(e.negotiation.superseded=!0),this.#se(e),e.requestId=t,e.outgoing=n;let s={controller:new AbortController,channel:null,ready:!1};return e.negotiation=s,s}#fe(e,t,n){let s=(e.operations??Promise.resolve()).then(()=>{if(this.#u(e,t))return n()});return e.operations=s.catch(()=>{}),s}#De(e,t,n){if(t.channel!==n){if(!this.#u(e,t)||t.channel){try{n.close()}catch{}return}t.channel=n,t.onOpen=()=>{t.ready&&this.#n("link-open",()=>this.#yt(e,t,n))},n.addEventListener("open",t.onOpen),n.readyState==="open"&&t.onOpen()}}#Ue(e,t){this.#u(e,t)&&(t.ready=!0,t.channel?.readyState==="open"&&t.onOpen())}async#ie(e,t=null){if(this.stopped||this.links.has(e)||this.dials.has(e)||this.dialChecks.has(e)||this.#H(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.#H(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 n=this.#Pe(!0),s=gl(),i={pubkey:e,pc:n,startedAt:I(),offerSentAt:0};t&&(i.discovery=t,this.discovery.allocated(t,i)),this.dials.set(e,i);let o=this.#He(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.#De(i,o,n.createDataChannel("relayswarm",{ordered:!0})),await this.#fe(i,o,async()=>{let a=await n.createOffer();if(!this.#u(i,o)||(await n.setLocalDescription(a),!this.#u(i,o))||(await Ji(n,1200,o.controller.signal,h=>{i.negotiation===o&&!o.superseded&&this.#Ne(n,"offer",h)}),!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.#re(),c=this.#ue(e,"offer",s,{sdp:n.localDescription.sdp,peers:this.links.size,...i.discovery?{requestedKey:i.discovery.key}:{},...l?{ticket:l}:{}});this.#g(n,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,n=0,s=t){if(this.dials.get(e.pubkey)!==e)return;this.dials.delete(e.pubkey),this.discovery.failed(e),this.#se(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()+(n>0?n:i)),this.#te()}async#mt({from:e,payload:t}){if(this.stopped||t.transport!==qn)return;let n=typeof t.payload?.sdp=="string"?t.payload.sdp:"";if(t.type==="answer"){let u=this.dials.get(e);if(!u?.outgoing||u.requestId!==t.requestId||!n)return;let p=u.negotiation;if(p.answerPending)return;if(this.#g(u.pc,"answer-received","authenticated"),!await this.#x(e,we(t.payload.ticket)?t.payload.ticket:null,"answerIncoming")){this.#u(u,p)&&this.#m(u,"failed",0,"admission");return}if(!this.#u(u,p)||!u.outgoing||u.requestId!==t.requestId||p.answerPending)return;p.answerPending=!0,this.#g(u.pc,"answer-admitted","accepted"),u.answerAt=I();try{await this.#fe(u,p,async()=>{await u.pc.setRemoteDescription({type:"answer",sdp:n}),this.#u(u,p)&&(this.#g(u.pc,"remote-installed","answer"),this.#Ue(u,p))})}catch(g){this.#u(u,p)&&(this.#o("answer",g),this.#m(u,"failed"))}return}if(t.type==="reject"){let u=this.dials.get(e);if(!u?.outgoing||u.requestId!==t.requestId)return;let p=this.#ft(t.payload);this.#m(u,"rejected",p.retryAfterMs),this.#$(e,!1),this.#pt(e,p);return}if(t.type!=="offer"||!n||(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,we(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.#ut(t.payload?.peers,t.payload?.requestedKey)){this.counters.offersRefused+=1,this.counters.evictionsUnavailable+=1,this.#ue(e,"reject",t.requestId,this.#dt(e));return}let u=this.#Pe(!1);a={pubkey:e,pc:u,startedAt:I(),offerSentAt:I()},this.dials.set(e,a),a.timer=this.#h(this.options.dialTimeoutMs,()=>this.#m(a,"timeout"))}let c=a.pc,h=this.#He(a,t.requestId,!1);l&&this.#g(c,"negotiation","glare-yield"),this.#g(c,"offer-admitted","accepted"),h.onDataChannel=u=>this.#De(a,h,u.channel),c.addEventListener("datachannel",h.onDataChannel);try{await this.#fe(a,h,async()=>{if(l){if(!await this.#x(e,we(t.payload.ticket)?t.payload.ticket:null,"glareBeforeRollback")){this.#u(a,h)&&this.#m(a,"failed",0,"admission");return}if(!this.#u(a,h))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,h)))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,we(t.payload.ticket)?t.payload.ticket:null,"glareAfterRollback")){this.#u(a,h)&&this.#m(a,"failed",0,"admission");return}if(!this.#u(a,h))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:n}),!this.#u(a,h))return;this.#g(c,"remote-installed","offer");let u=await c.createAnswer();if(!this.#u(a,h)||(await c.setLocalDescription(u),!this.#u(a,h))||(await Ji(c,1200,h.controller.signal,f=>{a.negotiation===h&&!h.superseded&&this.#Ne(c,"answer",f)}),!this.#u(a,h)))return;if(!await this.#x(e,we(t.payload.ticket)?t.payload.ticket:null,"answerBeforeSend")){this.#u(a,h)&&this.#m(a,"failed",0,"admission");return}if(!this.#u(a,h))return;let p=this.#re(),g=this.#ue(e,"answer",t.requestId,{sdp:c.localDescription.sdp,...p?{ticket:p}:{}});this.#g(c,g?"signal-send":"signal-failed","answer"),g?(this.counters.offersAccepted+=1,this.#Ue(a,h)):this.#m(a,"failed")})}catch(u){this.#u(a,h)&&(this.#o("offer",u),this.#m(a,"failed"))}}async#yt(e,t,n){if(!this.#u(e,t)||t.channel!==n||!t.ready){if(this.links.get(e.pubkey)?.channel!==n)try{n.close()}catch{}return}this.#g(e.pc,"channel-open","accepted"),this.#se(e,!1);let s=a=>{if(a.channel!==n)try{a.channel.close()}catch{}};e.pc.addEventListener("datachannel",s),this.dials.delete(e.pubkey),e.discovery&&(this.discovery.counters.opened++,this.#F(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&&Ke(this.signallingSamples,I()-e.offerSentAt);let i=this.#at({pubkey:e.pubkey,pc:e.pc,channel:n,maxSegmentBytes:this.options.maxSegmentBytes,onRequest:(a,l,c)=>this.#rt(a,l,c),onHaveChange:(a,l)=>{for(let c of[...this.haveWaiters])c(l);this.#A()},onScheduleChange:()=>{for(let a of[...this.haveWaiters])a();for(let a of[...this.peerLeaseWaiters])a();this.#A()},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.#A(),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 pl(e.pc);this.pairTypes[o]=(this.pairTypes[o]||0)+1;for(let a of[...this.haveWaiters])a()}};var Mh=Object.freeze({version:"0.4.4",sourceCommit:"a27c1804455699e9d8c8e5d48928680a3b6ba458"});export{Si as KIND_SEGMENT_COMMITMENT,ki as commitmentContent,xt as commitmentPieceSize,bl as createHlsSwarm,vn as finalizeEvent,Vt as generateSecretKey,Yt as matchFilter,Mh as relayswarmBuild,_t as segmentMediaContext,$t as verifyEvent}; +/*! RelaySwarm 0.4.4; public source 167b1c971c94456983da28d32dede00cd4c3123b. See media-peer-demo.NOTICE.txt. */ +function Zn(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 Xn(n){return{samples:n.length,offsetSeconds:n.length?Math.round(Math.max(...n)/1e3):null}}function Dt(n){return n instanceof Uint8Array||ArrayBuffer.isView(n)&&n.constructor.name==="Uint8Array"}function He(n,e=""){if(!Number.isSafeInteger(n)||n<0){let t=e&&`"${e}" `;throw new Error(`${t}expected integer >= 0, got ${n}`)}}function se(n,e,t=""){let r=Dt(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");He(n.outputLen),He(n.blockLen)}function Et(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 Qn(n,e){se(n,void 0,"digestInto() output");let t=e.outputLen;if(n.length='+t)}function Ge(...n){for(let e=0;e>>e}var es=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",to=Array.from({length:256},(n,e)=>e.toString(16).padStart(2,"0"));function De(n){if(se(n),es)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 Oe(n){if(typeof n!="string")throw new Error("hex string expected, got "+typeof n);if(es)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 rs=n=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,n])});function ns(n,e,t){return n&e^~n&t}function ss(n,e,t){return n&e^n&t^e&t}var or=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=ir(this.buffer)}update(e){Et(this),se(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 u=o;uh.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u>>3,m=ze(g,17)^ze(g,19)^g>>>10;tt[u]=m+tt[u-7]+f+tt[u-16]|0}let{A:r,B:s,C:i,D:o,E:a,F:l,G:c,H:h}=this;for(let u=0;u<64;u++){let p=ze(a,6)^ze(a,11)^ze(a,25),g=h+p+ns(a,l,c)+ro[u]+tt[u]|0,m=(ze(r,2)^ze(r,13)^ze(r,22))+ss(r,s,i)|0;h=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,h=h+this.H|0,this.set(r,s,i,o,a,l,c,h)}roundClean(){Ge(tt)}destroy(){this.set(0,0,0,0,0,0,0,0),Ge(this.buffer)}},Vr=class extends Kr{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=ts(()=>new Vr,rs(1));var Gr=BigInt(0),$r=BigInt(1);function Ut(n,e=""){if(typeof n!="boolean"){let t=e&&`"${e}" `;throw new Error(t+"expected boolean, got type="+typeof n)}return n}function is(n){if(typeof n=="bigint"){if(!ar(n))throw new Error("positive bigint expected, got "+n)}else He(n);return n}function zt(n){let e=is(n).toString(16);return e.length&1?"0"+e:e}function os(n){if(typeof n!="string")throw new Error("hex string expected, got "+typeof n);return n===""?Gr:BigInt("0x"+n)}function rt(n){return os(De(n))}function Yr(n){return os(De(no(se(n)).reverse()))}function lr(n,e){He(e),n=is(n);let t=Oe(n.toString(16).padStart(e*2,"0"));if(t.length!==e)throw new Error("number too large");return t}function Zr(n,e){return lr(n,e).reverse()}function no(n){return Uint8Array.from(n)}function as(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 ar=n=>typeof n=="bigint"&&Gr<=n;function so(n,e,t){return ar(n)&&ar(e)&&ar(t)&&e<=n&&nGr;n>>=$r,e+=1);return e}var qt=n=>($r<new Uint8Array(y),s=Uint8Array.of(),i=Uint8Array.of(0),o=Uint8Array.of(1),a=1e3,l=r(n),c=r(n),h=0,u=()=>{l.fill(1),c.fill(0),h=0},p=(...y)=>t(c,Se(l,...y)),g=(y=s)=>{c=p(i,y),l=p(),y.length!==0&&(c=p(o,y),l=p())},f=()=>{if(h++>=a)throw new Error("drbg: tried max amount of iterations");let y=0,v=[];for(;y{u(),g(y);let b;for(;!(b=v(f()));)g();return u(),b}}function Ft(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 Jr(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 Le=BigInt(0),Re=BigInt(1),gt=BigInt(2),ds=BigInt(3),fs=BigInt(4),ps=BigInt(5),io=BigInt(7),gs=BigInt(8),oo=BigInt(9),ms=BigInt(16);function qe(n,e){let t=n%e;return t>=Le?t:e+t}function Ne(n,e,t){let r=n;for(;e-- >Le;)r*=r,r%=t;return r}function hs(n,e){if(n===Le)throw new Error("invert: expected non-zero number");if(e<=Le)throw new Error("invert: expected positive modulus, got "+e);let t=qe(n,e),r=e,s=Le,i=Re,o=Re,a=Le;for(;t!==Le;){let c=r/t,h=r%t,u=s-o*c,p=i-a*c;r=t,t=h,s=o,i=a,o=u,a=p}if(r!==Re)throw new Error("invert: does not exist");return qe(s,e)}function en(n,e,t){if(!n.eql(n.sqr(e),t))throw new Error("Cannot find square root")}function ys(n,e){let t=(n.ORDER+Re)/fs,r=n.pow(e,t);return en(n,r,e),r}function ao(n,e){let t=(n.ORDER-ps)/gs,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 en(n,a,e),a}function lo(n){let e=At(n),t=bs(n),r=t(e,e.neg(e.ONE)),s=t(e,r),i=t(e,e.neg(r)),o=(n+io)/ms;return(a,l)=>{let c=a.pow(l,o),h=a.mul(c,r),u=a.mul(c,s),p=a.mul(c,i),g=a.eql(a.sqr(h),l),f=a.eql(a.sqr(u),l);c=a.cmov(c,h,g),h=a.cmov(p,u,f);let m=a.eql(a.sqr(h),l),y=a.cmov(c,h,m);return en(a,y,l),y}}function bs(n){if(n1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return ys;let i=s.pow(r,e),o=(e+Re)/gt;return function(l,c){if(l.is0(c))return c;if(us(l,c)!==1)throw new Error("Cannot find square root");let h=t,u=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===h)throw new Error("Cannot find square root");let y=Re<(r[s]="function",r),e);return Ft(n,t),n}function uo(n,e,t){if(tLe;)t&Re&&(r=n.mul(r,s)),s=n.sqr(s),t>>=Re;return r}function cr(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 us(n,e){let t=(n.ORDER-Re)/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 fo(n,e){e!==void 0&&He(e);let t=e!==void 0?e:n.toString(2).length,r=Math.ceil(t/8);return{nBitLength:t,nByteLength:r}}var Qr=class{ORDER;BITS;BYTES;isLE;ZERO=Le;ONE=Re;_lengths;_sqrt;_mod;constructor(e,t={}){if(e<=Le)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}=fo(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 qe(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return Le<=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?Yr(e):rt(e);if(a&&(l=qe(l,o)),!t&&!this.isValid(l))throw new Error("invalid field element: outside of range 0..ORDER");return l}invertBatch(e){return cr(this,e)}cmov(e,t,r){return r?t:e}};function At(n,e={}){return new Qr(n,e)}function ws(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 rn(n){let e=ws(n);return e+Math.ceil(e/2)}function hr(n,e,t=!1){se(n);let r=n.length,s=ws(e),i=rn(e);if(r<16||r1024)throw new Error("expected "+i+"-1024 bytes of input, got "+r);let o=t?Yr(n):rt(n),a=qe(o,e-Re)+Re;return t?Zr(a,s):lr(a,s)}var kt=BigInt(0),mt=BigInt(1);function jt(n,e){let t=e.negate();return n?t:e}function an(n,e){let t=cr(n.Fp,e.map(r=>r.Z));return e.map((r,s)=>n.fromAffine(r.toAffine(t[s])))}function Es(n,e){if(!Number.isSafeInteger(n)||n<=0||n>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+n)}function nn(n,e){Es(n,e);let t=Math.ceil(e/n)+1,r=2**(n-1),s=2**n,i=qt(n),o=BigInt(n);return{windows:t,windowSize:r,mask:i,maxNumber:s,shiftBy:o}}function vs(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,h=c+Math.abs(a)-1,u=a===0,p=a<0,g=e%2!==0;return{nextN:l,offset:h,isZero:u,isNeg:p,isNegF:g,offsetF:c}}var sn=new WeakMap,As=new WeakMap;function on(n){return As.get(n)||1}function xs(n){if(n!==kt)throw new Error("invalid wNAF")}var ur=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>kt;)t&mt&&(r=r.add(s)),s=s.double(),t>>=mt;return r}precomputeWindow(e,t){let{windows:r,windowSize:s}=nn(t,this.bits),i=[],o=e,a=o;for(let l=0;lkt||r>kt;)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 Ss(n,e,t){if(e){if(e.ORDER!==n)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return tn(e),e}else return At(n,{isLE:t})}function Ms(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>kt))throw new Error(`CURVE.${l} must be positive bigint`)}let s=Ss(e.p,t.Fp,r),i=Ss(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 dr(n,e){return function(r){let s=n(r);return{secretKey:s,publicKey:e(s)}}}var fr=class{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,t){if(pt(e),se(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 fr(n,e).update(t).digest();nt.create=(n,e)=>new fr(n,e);var Bs=(n,e)=>(n+(n>=0?e:-e)/Rs)/e;function po(n,e,t){let[[r,s],[i,o]]=e,a=Bs(o*n,t),l=Bs(-s*n,t),c=n-a*r-l*i,h=-a*s-l*o,u=c=g||h=g)throw new Error("splitScalar (endomorphism): failed, k="+n);return{k1neg:u,k1:c,k2neg:p,k2:h}}function cn(n){if(!["compact","recovered","der"].includes(n))throw new Error('Signature format must be "compact", "recovered", or "der"');return n}function ln(n,e){let t={};for(let r of Object.keys(e))t[r]=n[r]===void 0?e[r]:n[r];return Ut(t.lowS,"lowS"),Ut(t.prehash,"prehash"),t.format!==void 0&&cn(t.format),t}var hn=class extends Error{constructor(e=""){super(e)}},st={Err:hn,_tlv:{encode:(n,e)=>{let{Err:t}=st;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=zt(r);if(s.length/2&128)throw new t("tlv.encode: long form length too big");let i=r>127?zt(s.length/2|128):"";return zt(n)+i+s+e},decode(n,e){let{Err:t}=st,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 h of c)o=o<<8|h;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}=st;if(n{let{X:A,Y:x,Z:R}=d;if(r.eql(R,r.ONE))return{x:A,y:x};let P=d.is0();w==null&&(w=P?r.ONE:r.inv(R));let N=r.mul(A,w),M=r.mul(x,w),H=r.mul(R,w);if(P)return{x:r.ZERO,y:r.ZERO};if(!r.eql(H,r.ONE))throw new Error("invZ was invalid");return{x:N,y:M}}),L=Jr(d=>{if(d.is0()){if(e.allowInfinityPoint&&!r.is0(d.Y))return;throw new Error("bad point: ZERO")}let{x:w,y:A}=d.toAffine();if(!r.isValid(w)||!r.isValid(A))throw new Error("bad point: x or y not field elements");if(!y(w,A))throw new Error("bad point: equation left != right");if(!d.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function U(d,w,A,x,R){return A=new C(r.mul(A.X,d),A.Y,A.Z),w=jt(x,w),A=jt(R,A),w.add(A)}class C{static BASE=new C(i.Gx,i.Gy,r.ONE);static ZERO=new C(r.ZERO,r.ONE,r.ZERO);static Fp=r;static Fn=s;X;Y;Z;constructor(w,A,x){this.X=T("x",w),this.Y=T("y",A,!0),this.Z=T("z",x),Object.freeze(this)}static CURVE(){return i}static fromAffine(w){let{x:A,y:x}=w||{};if(!w||!r.isValid(A)||!r.isValid(x))throw new Error("invalid affine point");if(w instanceof C)throw new Error("projective point not allowed");return r.is0(A)&&r.is0(x)?C.ZERO:new C(A,x,r.ONE)}static fromBytes(w){let A=C.fromAffine(f(se(w,void 0,"point")));return A.assertValidity(),A}static fromHex(w){return C.fromBytes(Oe(w))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(w=8,A=!0){return O.createCache(this,w),A||this.multiply(pr),this}assertValidity(){L(this)}hasEvenY(){let{y:w}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(w)}equals(w){B(w);let{X:A,Y:x,Z:R}=this,{X:P,Y:N,Z:M}=w,H=r.eql(r.mul(A,M),r.mul(P,R)),D=r.eql(r.mul(x,M),r.mul(N,R));return H&&D}negate(){return new C(this.X,r.neg(this.Y),this.Z)}double(){let{a:w,b:A}=i,x=r.mul(A,pr),{X:R,Y:P,Z:N}=this,M=r.ZERO,H=r.ZERO,D=r.ZERO,q=r.mul(R,R),ee=r.mul(P,P),j=r.mul(N,N),V=r.mul(R,P);return V=r.add(V,V),D=r.mul(R,N),D=r.add(D,D),M=r.mul(w,D),H=r.mul(x,j),H=r.add(M,H),M=r.sub(ee,H),H=r.add(ee,H),H=r.mul(M,H),M=r.mul(V,M),D=r.mul(x,D),j=r.mul(w,j),V=r.sub(q,j),V=r.mul(w,V),V=r.add(V,D),D=r.add(q,q),q=r.add(D,q),q=r.add(q,j),q=r.mul(q,V),H=r.add(H,q),j=r.mul(P,N),j=r.add(j,j),q=r.mul(j,V),M=r.sub(M,q),D=r.mul(j,ee),D=r.add(D,D),D=r.add(D,D),new C(M,H,D)}add(w){B(w);let{X:A,Y:x,Z:R}=this,{X:P,Y:N,Z:M}=w,H=r.ZERO,D=r.ZERO,q=r.ZERO,ee=i.a,j=r.mul(i.b,pr),V=r.mul(A,P),re=r.mul(x,N),ae=r.mul(R,M),ge=r.add(A,x),ne=r.add(P,N);ge=r.mul(ge,ne),ne=r.add(V,re),ge=r.sub(ge,ne),ne=r.add(A,R);let pe=r.add(P,M);return ne=r.mul(ne,pe),pe=r.add(V,ae),ne=r.sub(ne,pe),pe=r.add(x,R),H=r.add(N,M),pe=r.mul(pe,H),H=r.add(re,ae),pe=r.sub(pe,H),q=r.mul(ee,ne),H=r.mul(j,ae),q=r.add(H,q),H=r.sub(re,q),q=r.add(re,q),D=r.mul(H,q),re=r.add(V,V),re=r.add(re,V),ae=r.mul(ee,ae),ne=r.mul(j,ne),re=r.add(re,ae),ae=r.sub(V,ae),ae=r.mul(ee,ae),ne=r.add(ne,ae),V=r.mul(re,ne),D=r.add(D,V),V=r.mul(pe,ne),H=r.mul(ge,H),H=r.sub(H,V),V=r.mul(ge,re),q=r.mul(pe,q),q=r.add(q,V),new C(H,D,q)}subtract(w){return this.add(w.negate())}is0(){return this.equals(C.ZERO)}multiply(w){let{endo:A}=e;if(!s.isValidNot0(w))throw new Error("invalid scalar: out of range");let x,R,P=N=>O.cached(this,N,M=>an(C,M));if(A){let{k1neg:N,k1:M,k2neg:H,k2:D}=$(w),{p:q,f:ee}=P(M),{p:j,f:V}=P(D);R=ee.add(V),x=U(A.beta,q,j,N,H)}else{let{p:N,f:M}=P(w);x=N,R=M}return an(C,[x,R])[0]}multiplyUnsafe(w){let{endo:A}=e,x=this;if(!s.isValid(w))throw new Error("invalid scalar: out of range");if(w===Xe||x.is0())return C.ZERO;if(w===Mt)return x;if(O.hasCache(this))return this.multiply(w);if(A){let{k1neg:R,k1:P,k2neg:N,k2:M}=$(w),{p1:H,p2:D}=ks(C,x,P,M);return U(A.beta,H,D,R,N)}else return O.unsafe(x,w)}toAffine(w){return S(this,w)}isTorsionFree(){let{isTorsionFree:w}=e;return o===Mt?!0:w?w(C,this):O.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:w}=e;return o===Mt?this:w?w(C,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(w=!0){return Ut(w,"isCompressed"),this.assertValidity(),g(C,this,w)}toHex(w=!0){return De(this.toBytes(w))}toString(){return``}}let F=s.BITS,O=new ur(C,e.endo?Math.ceil(F/2):F);return C.BASE.precompute(8),C}function Ls(n){return Uint8Array.of(n?2:3)}function _s(n,e){return{secretKey:e.BYTES,publicKey:1+n.BYTES,publicKeyUncompressed:1+2*n.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function mo(n,e={}){let{Fn:t}=n,r=e.randomBytes||Ye,s=Object.assign(_s(n.Fp,t),{seed:rn(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:y}=s;try{let v=g.length;return f===!0&&v!==m||f===!1&&v!==y?!1:!!n.fromBytes(g)}catch{return!1}}function a(g=r(s.seed)){return hr(se(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:y}=s;if(!Dt(g)||"_lengths"in t&&t._lengths||f===m)return;let v=se(g,void 0,"key").length;return v===m||v===y}function h(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 y=t.fromBytes(g);return n.fromBytes(f).multiply(y).toBytes(m)}let u={isValidSecretKey:i,isValidPublicKey:o,randomSecretKey:a},p=dr(a,l);return Object.freeze({getPublicKey:l,getSharedSecret:h,keygen:p,Point:n,utils:u,lengths:s})}function Os(n,e,t={}){pt(e),Ft(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),t=Object.assign({},t);let r=t.randomBytes||Ye,s=t.hmac||((A,x)=>nt(e,A,x)),{Fp:i,Fn:o}=n,{ORDER:a,BITS:l}=o,{keygen:c,getPublicKey:h,getSharedSecret:u,utils:p,lengths:g}=mo(n,t),f={prehash:!0,lowS:typeof t.lowS=="boolean"?t.lowS:!0,format:"compact",extraEntropy:!1},m=a*Rs>Mt;return A>x}function v(A,x){if(!o.isValidNot0(x))throw new Error(`invalid signature ${A}: out of range 1..Point.Fn.ORDER`);return x}function b(){if(m)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function T(A,x){cn(x);let R=g.signature,P=x==="compact"?R:x==="recovered"?R+1:void 0;return se(A,P)}class B{r;s;recovery;constructor(x,R,P){if(this.r=v("r",x),this.s=v("s",R),P!=null){if(b(),![0,1,2,3].includes(P))throw new Error("invalid recovery id");this.recovery=P}Object.freeze(this)}static fromBytes(x,R=f.format){T(x,R);let P;if(R==="der"){let{r:D,s:q}=st.toSig(se(x));return new B(D,q)}R==="recovered"&&(P=x[0],R="compact",x=x.subarray(1));let N=g.signature/2,M=x.subarray(0,N),H=x.subarray(N,N*2);return new B(o.fromBytes(M),o.fromBytes(H),P)}static fromHex(x,R){return this.fromBytes(Oe(x),R)}assertRecovery(){let{recovery:x}=this;if(x==null)throw new Error("invalid recovery id: must be present");return x}addRecoveryBit(x){return new B(this.r,this.s,x)}recoverPublicKey(x){let{r:R,s:P}=this,N=this.assertRecovery(),M=N===2||N===3?R+a:R;if(!i.isValid(M))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let H=i.toBytes(M),D=n.fromBytes(Se(Ls((N&1)===0),H)),q=o.inv(M),ee=S(se(x,void 0,"msgHash")),j=o.create(-ee*q),V=o.create(P*q),re=n.BASE.multiplyUnsafe(j).add(D.multiplyUnsafe(V));if(re.is0())throw new Error("invalid recovery: point at infinify");return re.assertValidity(),re}hasHighS(){return y(this.s)}toBytes(x=f.format){if(cn(x),x==="der")return Oe(st.hexFromSig(this));let{r:R,s:P}=this,N=o.toBytes(R),M=o.toBytes(P);return x==="recovered"?(b(),Se(Uint8Array.of(this.assertRecovery()),N,M)):Se(N,M)}toHex(x){return De(this.toBytes(x))}}let $=t.bits2int||function(x){if(x.length>8192)throw new Error("input is too large");let R=rt(x),P=x.length*8-l;return P>0?R>>BigInt(P):R},S=t.bits2int_modN||function(x){return o.create($(x))},L=qt(l);function U(A){return ls("num < 2^"+l,A,Xe,L),o.toBytes(A)}function C(A,x){return se(A,void 0,"message"),x?se(e(A),void 0,"prehashed message"):A}function F(A,x,R){let{lowS:P,prehash:N,extraEntropy:M}=ln(R,f);A=C(A,N);let H=S(A),D=o.fromBytes(x);if(!o.isValidNot0(D))throw new Error("invalid private key");let q=[U(D),U(H)];if(M!=null&&M!==!1){let re=M===!0?r(g.secretKey):M;q.push(se(re,void 0,"extraEntropy"))}let ee=Se(...q),j=H;function V(re){let ae=$(re);if(!o.isValidNot0(ae))return;let ge=o.inv(ae),ne=n.BASE.multiply(ae).toAffine(),pe=o.create(ne.x);if(pe===Xe)return;let Q=o.create(ge*o.create(j+pe*D));if(Q===Xe)return;let me=(ne.x===pe?0:2)|Number(ne.y&Mt),et=Q;return P&&y(Q)&&(et=o.neg(Q),me^=1),new B(pe,et,m?void 0:me)}return{seed:ee,k2sig:V}}function O(A,x,R={}){let{seed:P,k2sig:N}=F(A,x,R);return cs(e.outputLen,o.BYTES,s)(P,N).toBytes(R.format)}function d(A,x,R,P={}){let{lowS:N,prehash:M,format:H}=ln(P,f);if(R=se(R,void 0,"publicKey"),x=C(x,M),!Dt(A)){let D=A instanceof B?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+D)}T(A,H);try{let D=B.fromBytes(A,H),q=n.fromBytes(R);if(N&&D.hasHighS())return!1;let{r:ee,s:j}=D,V=S(x),re=o.inv(j),ae=o.create(V*re),ge=o.create(ee*re),ne=n.BASE.multiplyUnsafe(ae).add(q.multiplyUnsafe(ge));return ne.is0()?!1:o.create(ne.x)===ee}catch{return!1}}function w(A,x,R={}){let{prehash:P}=ln(R,f);return x=C(x,P),B.fromBytes(A,"recovered").recoverPublicKey(x).toBytes()}return Object.freeze({keygen:c,getPublicKey:h,getSharedSecret:u,utils:p,lengths:g,Point:n,sign:O,verify:d,recoverPublicKey:w,Signature:B,hash:e})}var yr={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},yo={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},bo=BigInt(0),un=BigInt(2);function wo(n){let e=yr.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,h=c*c*n%e,u=Ne(h,t,e)*h%e,p=Ne(u,t,e)*h%e,g=Ne(p,un,e)*c%e,f=Ne(g,s,e)*g%e,m=Ne(f,i,e)*f%e,y=Ne(m,a,e)*m%e,v=Ne(y,l,e)*y%e,b=Ne(v,a,e)*m%e,T=Ne(b,t,e)*h%e,B=Ne(T,o,e)*f%e,$=Ne(B,r,e)*c%e,S=Ne($,un,e);if(!gr.eql(gr.sqr(S),n))throw new Error("Cannot find square root");return S}var gr=At(yr.p,{sqrt:wo}),yt=Ts(yr,{Fp:gr,endo:yo}),Ns=Os(yt,Fe),Is={};function mr(n,...e){let t=Is[n];if(t===void 0){let r=Fe(as(n));t=Se(r,r),Is[n]=t}return Fe(Se(t,...e))}var fn=n=>n.toBytes(!0).slice(1),pn=n=>n%un===bo;function dn(n){let{Fn:e,BASE:t}=yt,r=e.fromBytes(n),s=t.multiply(r);return{scalar:pn(s.y)?r:e.neg(r),bytes:fn(s)}}function Ps(n){let e=gr;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);pn(s)||(s=e.neg(s));let i=yt.fromAffine({x:n,y:s});return i.assertValidity(),i}var Wt=rt;function Hs(...n){return yt.Fn.create(Wt(mr("BIP0340/challenge",...n)))}function Cs(n){return dn(n).bytes}function vo(n,e,t=Ye(32)){let{Fn:r}=yt,s=se(n,void 0,"message"),{bytes:i,scalar:o}=dn(e),a=se(t,32,"auxRand"),l=r.toBytes(o^Wt(mr("BIP0340/aux",a))),c=mr("BIP0340/nonce",l,i,s),{bytes:h,scalar:u}=dn(c),p=Hs(h,i,s),g=new Uint8Array(64);if(g.set(h,0),g.set(r.toBytes(r.create(u+p*o)),32),!Ds(g,s,i))throw new Error("sign: Invalid signature produced");return g}function Ds(n,e,t){let{Fp:r,Fn:s,BASE:i}=yt,o=se(n,64,"signature"),a=se(e,void 0,"message"),l=se(t,32,"publicKey");try{let c=Ps(Wt(l)),h=Wt(o.subarray(0,32));if(!r.isValidNot0(h))return!1;let u=Wt(o.subarray(32,64));if(!s.isValidNot0(u))return!1;let p=Hs(s.toBytes(h),fn(c),a),g=i.multiplyUnsafe(u).add(c.multiplyUnsafe(s.neg(p))),{x:f,y:m}=g.toAffine();return!(g.is0()||!pn(m)||f!==h)}catch{return!1}}var Bt=(()=>{let t=(r=Ye(48))=>hr(r,yr.n);return{keygen:dr(t,Cs),getPublicKey:Cs,sign:vo,verify:Ds,Point:yt,utils:{randomSecretKey:t,taggedHash:mr,lift_x:Ps,pointToBytes:fn},lengths:{secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:64,seed:48}}})();var tc=new TextDecoder("utf-8"),xo=new TextEncoder;function So(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 Rt=Symbol("verified"),Eo=n=>n instanceof Object;function Ao(n){if(!Eo(n)||typeof n.kind!="number"||typeof n.content!="string"||typeof n.created_at!="number"||typeof n.pubkey!="string"||!So(n.pubkey)||!Array.isArray(n.tags))return!1;for(let e=0;e{function t(r,...s){if(Ee(r,void 0,"key"),!To)throw new Error("Non little-endian hardware is not yet supported");if(n.nonceLength!==void 0){let h=s[0];Ee(h,n.varSizeNonce?void 0:n.nonceLength,"nonce")}let i=n.tagLength;i&&s[1]!==void 0&&Ee(s[1],void 0,"AAD");let o=e(r,...s),a=(h,u)=>{if(u!==void 0){if(h!==2)throw new Error("cipher output not supported");Ee(u,void 0,"output")}},l=!1;return{encrypt(h,u){if(l)throw new Error("cannot encrypt() twice with same key + nonce");return l=!0,Ee(h),a(o.encrypt.length,u),o.encrypt(h,u)},decrypt(h,u){if(Ee(h),i&&h.lengthUint8Array.from(n.split(""),e=>e.charCodeAt(0)),_o=Ws("expand 16-byte k"),Oo=Ws("expand 32-byte k"),Io=Je(_o),Co=Je(Oo);function Y(n,e){return n<>>32-e}function bn(n){return n.byteOffset%4===0}var Er=64,No=16,Ks=2**32-1,js=Uint32Array.of();function Po(n,e,t,r,s,i,o,a){let l=s.length,c=new Uint8Array(Er),h=Je(c),u=bn(s)&&bn(i),p=u?Je(s):js,g=u?Je(i):js;for(let f=0;f=Ks)throw new Error("arx: counter overflow");let m=Math.min(Er,l-f);if(u&&m===Er){let y=f/4;if(f%4!==0)throw new Error("arx: invalid block position");for(let v=0,b;v{Ee(a,void 0,"key"),Ee(l,void 0,"nonce"),Ee(c,void 0,"data");let p=c.length;if(h===void 0&&(h=new Uint8Array(p)),Ee(h,void 0,"output"),xr(u),u<0||u>=Ks)throw new Error("arx: counter overflow");if(h.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 h=0;h<8;h++)this.pad[h]=ke(e,16+2*h)}process(e,t,r=!1){let s=r?0:2048,{h:i,r:o}=this,a=o[0],l=o[1],c=o[2],h=o[3],u=o[4],p=o[5],g=o[6],f=o[7],m=o[8],y=o[9],v=ke(e,t+0),b=ke(e,t+2),T=ke(e,t+4),B=ke(e,t+6),$=ke(e,t+8),S=ke(e,t+10),L=ke(e,t+12),U=ke(e,t+14),C=i[0]+(v&8191),F=i[1]+((v>>>13|b<<3)&8191),O=i[2]+((b>>>10|T<<6)&8191),d=i[3]+((T>>>7|B<<9)&8191),w=i[4]+((B>>>4|$<<12)&8191),A=i[5]+($>>>1&8191),x=i[6]+(($>>>14|S<<2)&8191),R=i[7]+((S>>>11|L<<5)&8191),P=i[8]+((L>>>8|U<<8)&8191),N=i[9]+(U>>>5|s),M=0,H=M+C*a+F*(5*y)+O*(5*m)+d*(5*f)+w*(5*g);M=H>>>13,H&=8191,H+=A*(5*p)+x*(5*u)+R*(5*h)+P*(5*c)+N*(5*l),M+=H>>>13,H&=8191;let D=M+C*l+F*a+O*(5*y)+d*(5*m)+w*(5*f);M=D>>>13,D&=8191,D+=A*(5*g)+x*(5*p)+R*(5*u)+P*(5*h)+N*(5*c),M+=D>>>13,D&=8191;let q=M+C*c+F*l+O*a+d*(5*y)+w*(5*m);M=q>>>13,q&=8191,q+=A*(5*f)+x*(5*g)+R*(5*p)+P*(5*u)+N*(5*h),M+=q>>>13,q&=8191;let ee=M+C*h+F*c+O*l+d*a+w*(5*y);M=ee>>>13,ee&=8191,ee+=A*(5*m)+x*(5*f)+R*(5*g)+P*(5*p)+N*(5*u),M+=ee>>>13,ee&=8191;let j=M+C*u+F*h+O*c+d*l+w*a;M=j>>>13,j&=8191,j+=A*(5*y)+x*(5*m)+R*(5*f)+P*(5*g)+N*(5*p),M+=j>>>13,j&=8191;let V=M+C*p+F*u+O*h+d*c+w*l;M=V>>>13,V&=8191,V+=A*a+x*(5*y)+R*(5*m)+P*(5*f)+N*(5*g),M+=V>>>13,V&=8191;let re=M+C*g+F*p+O*u+d*h+w*c;M=re>>>13,re&=8191,re+=A*l+x*a+R*(5*y)+P*(5*m)+N*(5*f),M+=re>>>13,re&=8191;let ae=M+C*f+F*g+O*p+d*u+w*h;M=ae>>>13,ae&=8191,ae+=A*c+x*l+R*a+P*(5*y)+N*(5*m),M+=ae>>>13,ae&=8191;let ge=M+C*m+F*f+O*g+d*p+w*u;M=ge>>>13,ge&=8191,ge+=A*h+x*c+R*l+P*a+N*(5*y),M+=ge>>>13,ge&=8191;let ne=M+C*y+F*m+O*f+d*g+w*p;M=ne>>>13,ne&=8191,ne+=A*u+x*h+R*c+P*l+N*a,M+=ne>>>13,ne&=8191,M=(M<<2)+M|0,M=M+H|0,H=M&8191,M=M>>>13,D+=M,i[0]=H,i[1]=D,i[2]=q,i[3]=ee,i[4]=j,i[5]=V,i[6]=re,i[7]=ae,i[8]=ge,i[9]=ne}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){gn(this),Ee(e),e=Tt(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 Ho(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 Vs=Ho(n=>new vn(n));function Ys(n,e,t,r,s,i=20){let o=n[0],a=n[1],l=n[2],c=n[3],h=e[0],u=e[1],p=e[2],g=e[3],f=e[4],m=e[5],y=e[6],v=e[7],b=s,T=t[0],B=t[1],$=t[2],S=o,L=a,U=l,C=c,F=h,O=u,d=p,w=g,A=f,x=m,R=y,P=v,N=b,M=T,H=B,D=$;for(let ee=0;ee{n.update(e);let t=e.length%16;t&&n.update(zo.subarray(t))},qo=new Uint8Array(32);function Gs(n,e,t,r,s){s!==void 0&&Ee(s,void 0,"AAD");let i=n(e,t,qo),o=Fs(r.length,s?s.length:0,!0),a=Vs.create(i);s&&$s(a,s),$s(a,r),a.update(o);let l=a.digest();return Qe(i,o),l}var Zs=n=>(e,t,r)=>({encrypt(i,o){let a=i.length;o=yn(a+16,o,!1),o.set(i);let l=o.subarray(0,-16);n(e,t,l,l,1);let c=Gs(n,e,t,l,r);return o.set(c,a),Qe(c),o},decrypt(i,o){o=yn(i.length-16,o,!1);let a=i.subarray(0,-16),l=i.subarray(-16),c=Gs(n,e,t,a,r);if(!Sr(l,c))throw new Error("invalid tag");return o.set(i.subarray(0,-16)),n(e,t,o,o,1),Qe(c),o}}),wc=mn({blockSize:64,nonceLength:12,tagLength:16},Zs(Ar)),vc=mn({blockSize:64,nonceLength:24,tagLength:16},Zs(Uo));function Js(n,e,t){return pt(n),t===void 0&&(t=new Uint8Array(n.outputLen)),nt(n,t,e)}var xn=Uint8Array.of(0),Xs=Uint8Array.of();function Qs(n,e,t,r=32){pt(n),He(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=Xs:se(t,void 0,"info");let o=new Uint8Array(i*s),a=nt.create(n,e),l=a._cloneInto(),c=new Uint8Array(a.outputLen);for(let h=0;htypeof t=="string"):e.every(t=>Number.isSafeInteger(t)):!1}function Gt(n,e){if(typeof e!="string")throw new Error(`${n}: string expected`);return!0}function An(n){if(!Number.isSafeInteger(n))throw new Error(`invalid integer: ${n}`)}function En(n){if(!Array.isArray(n))throw new Error("array expected")}function kr(n,e){if(!ri(!0,e))throw new Error(`${n}: array of strings expected`)}function jo(n,e){if(!ri(!1,e))throw new Error(`${n}: array of numbers expected`)}function Wo(...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 Ko(n){let e=typeof n=="string"?n.split(""):n,t=e.length;kr("alphabet",e);let r=new Map(e.map((s,i)=>[s,i]));return{encode:s=>(En(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=>(En(s),s.map(i=>{Gt("alphabet.decode",i);let o=r.get(i);if(o===void 0)throw new Error(`Unknown letter: "${i}". Allowed: ${n}`);return o}))}}function Vo(n=""){return Gt("join",n),{encode:e=>(kr("join.decode",e),e.join(n)),decode:e=>(Gt("join.decode",e),e.split(n))}}function $o(n,e="="){return An(n),Gt("padding",e),{encode(t){for(kr("padding.encode",t);t.length*n%8;)t.push(e);return t},decode(t){kr("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 ni=(n,e)=>e===0?n:ni(e,n%e),Mr=(n,e)=>n+(e-ni(n,e)),Sn=(()=>{let n=[];for(let e=0;e<40;e++)n.push(2**e);return n})();function ei(n,e,t,r){if(En(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(Mr(e,t)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${t} carryBits=${Mr(e,t)}`);let s=0,i=0,o=Sn[e],a=Sn[t]-1,l=[];for(let c of n){if(An(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 h=Sn[i];if(h===void 0)throw new Error("invalid carry");s&=h-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 Go(n,e=!1){if(An(n),n<=0||n>32)throw new Error("radix2: bits should be in (0..32]");if(Mr(8,n)>32||Mr(n,8)>32)throw new Error("radix2: carry overflow");return{encode:t=>{if(!ti(t))throw new Error("radix2.encode input should be Uint8Array");return ei(Array.from(t),8,n,!e)},decode:t=>(jo("radix2.decode",t),Uint8Array.from(ei(t,n,8,e)))}}var Yo=typeof Uint8Array.from([]).toBase64=="function"&&typeof Uint8Array.fromBase64=="function",Zo=(n,e)=>{Gt("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"})},kn=Yo?{encode(n){return Fo(n),n.toBase64()},decode(n){return Zo(n,!1)}}:Wo(Go(6),Ko("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),$o(6),Vo(""));var Xo=new TextDecoder("utf-8"),si=new TextEncoder,Mn=1,Bn=4294967295,Rn=65536;function Jo(n,e){let t=Ns.getSharedSecret(n,Oe("02"+e)).subarray(1,33);return Js(Fe,t,si.encode("nip44-v2"))}function ii(n,e){let t=Qs(Fe,n,e,76);return{chacha_key:t.subarray(0,32),chacha_nonce:t.subarray(32,44),hmac_key:t.subarray(44,76)}}function Tn(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 Qo(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 ea(n){if(!Number.isSafeInteger(n)||nBn)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 oi(n){let e=si.encode(n),t=e.length;if(tBn)throw new Error("invalid plaintext size: must be between 1 and 4294967295 bytes");let r=t>=Rn?Se(new Uint8Array([0,0]),ea(t)):Qo(t),s=new Uint8Array(Tn(t)-t);return Se(r,e,s)}function ai(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),rBn||i.length!==r||n.length!==s+Tn(r))throw new Error("invalid padding");return Xo.decode(i)}function li(n,e,t){if(t.length!==32)throw new Error("AAD associated data must be 32 bytes");let r=Se(t,e);return nt(Fe,n,r)}function ta(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=kn.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 ra(n,e,t=Ye(32)){let{chacha_key:r,chacha_nonce:s,hmac_key:i}=ii(e,t),o=oi(n),a=Ar(r,s,o),l=li(i,a,t);return kn.encode(Se(new Uint8Array([2]),t,a,l))}function na(n,e){let{nonce:t,ciphertext:r,mac:s}=ta(n),{chacha_key:i,chacha_nonce:o,hmac_key:a}=ii(e,t),l=li(a,r,t);if(!Sr(l,s))throw new Error("invalid MAC");let c=Ar(i,o,r);return ai(c)}var Br={utils:{getConversationKey:Jo,calcPaddedLen:Tn,pad:oi,unpad:ai},encrypt:ra,decrypt:na};function Yt(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 Rr=3,Tr=24170,Ln=24171,Lr="x",Zt=/^[0-9a-f]{64}$/u,sa=/^[a-z0-9](?:[a-z0-9-]{0,31})$/u,ia=1*1024*1024,ci=16*1024,oa=64*1024,hi=8*1024,aa=2*1024,ui=30,la=64,ca=256,di=new TextEncoder;function bt(n){return typeof n=="string"?di.encode(n).byteLength:n instanceof ArrayBuffer||ArrayBuffer.isView(n)?n.byteLength:di.encode(String(n)).byteLength}function ha(n){return Array.from(globalThis.crypto.getRandomValues(new Uint8Array(n)),e=>e.toString(16).padStart(2,"0")).join("")}function yi(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 _n=n=>Math.min(Number.MAX_SAFE_INTEGER,n);function fi(n,e){let t=yi(n,e);return t.length===1?t[0]:null}function pi(n){let e=JSON.parse(n);if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Expected a JSON object.");return e}function it(n){return typeof n=="string"&&sa.test(n)}function gi(n){return typeof n=="string"&&n.length>=8&&n.length<=64&&/^[a-zA-Z0-9_-]+$/u.test(n)}function ua(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 _r=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(ua))],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.#n().finally(()=>{this.connecting=null}),this.connecting)}async#n(){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,h]of this.subscriptions)i.send(JSON.stringify(["REQ",c,h]));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)>ia)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&&!Yt(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=ha(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()}},Or=class{#n=null;#t=null;#e=new Map;#s=null;constructor({pool:e,swarmId:t,secretKey:r=Vt(),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=Us(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={[`#${Lr}`]:[this.swarmId],since:Math.floor(Date.now()/1e3)-2};try{this.#t=this.pool.onRelayOpen?.(t=>{if(!this.started||!this.#n)return;let r=Math.floor(Date.now()/1e3)-this.#n.created_at;if(!Number.isFinite(r)||!Number.isFinite(this.maxEventAgeSeconds)||r<-ui||r>this.maxEventAgeSeconds){this.#n=null;return}t(this.#n)}),this.subscriptionId=this.pool.subscribe({...e,since:Math.floor(Date.now()/1e3)-this.maxEventAgeSeconds,kinds:[Tr]}),this.subscriptionIds.push(this.subscriptionId),this.subscriptionIds.push(this.pool.subscribe({...e,kinds:[Ln],"#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.#n=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&&!we(i))throw new Error("Invalid presence ticket.");if(!it(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=>!Zt.test(c)))throw new Error("Invalid object hash list.");let o=t.map(c=>{if(!c||typeof c!="object"||!it(c.type)||!Zt.test(c.publicKey)||c.obj!==void 0&&!mi(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:Rr,role:e,transports:o,have:[...new Set(r)],...s===void 0?{}:{open:!!s},...i===void 0?{}:{ticket:i}});if(bt(a)>ci)throw new Error("Presence payload is too large.");let l=wr({kind:Tr,created_at:Math.floor(Date.now()/1e3),tags:[[Lr,this.swarmId]],content:a},this.secretKey);return this.pool.publish(l),this.#n=JSON.parse(JSON.stringify(l)),l}sendSignal(e,{type:t,transport:r,requestId:s,payload:i={}}={}){if(!Zt.test(e))throw new Error("Invalid signal recipient.");if(!it(t)||!it(r)||!gi(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:Rr,type:t,transport:r,requestId:s,payload:i});if(bt(o)>hi)throw new Error("Signal payload is too large.");let a=Br.encrypt(o,this.#r(e)),l=wr({kind:Ln,created_at:Math.floor(Date.now()/1e3),tags:[[Lr,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 h=!1;try{h=t(c)}catch(u){clearTimeout(l),e.delete(a),o(u);return}h&&(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!==Tr&&e.kind!==Ln||!Number.isSafeInteger(e.created_at)||fi(e,Lr)!==this.swarmId)return;let t=Math.floor(Date.now()/1e3)-e.created_at;if(t<-ui){this.clock.aheadRejected=_n(this.clock.aheadRejected+1),this.clock.maxAheadSeconds=Math.max(this.clock.maxAheadSeconds,_n(-t));return}if(t>this.maxEventAgeSeconds){this.clock.staleRejected=_n(this.clock.staleRejected+1);return}try{e.kind===Tr?this.#c(e):this.#o(e)}catch{}}#c(e){if(bt(e.content)>ci||yi(e,"p").length!==0)return;let t=pi(e.content);if(t.v!==Rr||!it(t.role)||!Array.isArray(t.transports)||t.transports.length>8||!Array.isArray(t.have)||t.have.length>32||t.have.some(o=>!Zt.test(o)))return;let r=t.transports.map(o=>{if(!o||typeof o!="object"||!it(o.type)||!Zt.test(o.publicKey))throw new Error("Invalid transport capability.");return{type:o.type,publicKey:o.publicKey,...mi(o.obj)?{obj:o.obj}:{}}}),s=typeof t.open=="boolean"?t.open:null,i=we(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)>oa||fi(e,"p")!==this.pubkey)return;let t=Br.decrypt(e.content,this.#r(e.pubkey));if(bt(t)>hi)return;let r=pi(t);r.v!==Rr||!it(r.type)||!it(r.transport)||!gi(r.requestId)||!r.payload||typeof r.payload!="object"||Array.isArray(r.payload)||(this.clock.signalAges.length>=la&&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}))}#r(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=Br.utils.getConversationKey(this.secretKey,e),this.#e.size>=ca&&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.#n=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 mi(n){return Number.isSafeInteger(n)&&n>=1&&n<=15}function we(n){return typeof n=="string"&&n.length>0&&bt(n)<=aa}var On=/^[0-9a-f]{64}$/u,bi="relayswarm-abandon";var wi=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"]),ot=class{static ABANDON_REASON=bi;#n=!1;constructor({pubkey:e,pc:t,channel:r,maxSegmentBytes:s,onRequest:i,onHaveChange:o,onScheduleChange:a,onClose:l,onUploadCancelled:c,maxQueuedRequests:h=4,drainTimeoutMs:u=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=h,this.drainTimeoutMs=u,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=(h,u=null)=>{if(!l&&(l=!0,typeof i=="function"))try{let p=null;if(Number.isFinite(a))try{p=performance.now()-a}catch{}let g=u?.received??0,f=Number.isFinite(u?.firstByteAt)&&Number.isFinite(a)?u.firstByteAt-a:null;i({outcome:h,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:u?u.size>=0:!1,draining:u?.draining===!0,closeReason:wi.has(this.closeReason)?this.closeReason:null})}catch{}};if(this.closed||this.pending||r?.aborted){let h=Promise.resolve(null);return c(this.closed?"closed":this.pending?"busy":"abort"),h}return new Promise(h=>{let u=this.nextId++,p=b=>{clearTimeout(this.pending.timer),r?.removeEventListener("abort",m),h(b)},g=(b,T=b?"payload":"none",B=!0)=>{if(this.pending?.id!==u)return;let $=this.pending,S=$.draining;p(b),this.pending=null,b&&(this.lastDeliveredAt=Date.now()),S&&!this.closed&&this.onScheduleChange?.(this),B&&c(T,$)},f=b=>{let T=this.pending;if(!T||T.id!==u||T.draining)return;let B=!1;try{B=this.channel.ordered===!0&&this.channel.maxRetransmits===null&&this.channel.maxPacketLifeTime===null&&this.channel.readyState==="open"}catch{}let $=b!=="request-abort"?"timeout":r?.reason===bi?"abandoned":"abort";if(!B){g(null,$,!1);try{this.close(b)}finally{c($,T)}return}T.draining=!0,T.parts.length=0,p(null),T.timer=setTimeout(()=>{this.pending===T&&T.draining&&this.close(b)},this.drainTimeoutMs),c($,T),T.cancelled=this.#t({t:"cancel",id:u})},m=()=>f("request-abort"),y=()=>f("request-timeout"),v=typeof o=="function"?b=>{try{o(b.received,b.size,Number.isFinite(a)?b.firstByteAt-a:null)}catch{}}:null;this.pending={id:u,key:e,expectedSize:s,size:-1,parts:[],chunks:0,received:0,firstByteAt:null,progress:v,draining:!1,cancelled:!1,finish:g,timer:setTimeout(y,Math.max(1,t))},r?.addEventListener("abort",m,{once:!0}),this.#t({t:"want",id:u,k:e})||g(null,"send-error")})}close(e="host"){if(!this.closed){this.closed=!0,this.closeReason=wi.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"&&On.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"||!On.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.#n?"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.#n=!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 vi(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 da=n=>vi(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 da(this.recentFirstBytes)}rate(){let e=this.firstByteMs(),t=e===null?[]:this.recentRates.filter(({flowMs:r})=>r>=e*3);return vi((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),h=a.length&&(!c.length||this.turn===0&&i>=100);this.turn=(this.turn+1)%4;let u=h?a:c.length?c:l,p=f=>{let m=this.summary(f);return h?m.lastSelected:(this.estimate(f,s)??1e3)*(1+m.failureRate*4)},g=u.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 Xt=/^[0-9a-f]{64}$/u,fa=4,pa=1e4,ga=8,xi=2e4,Lt=class{constructor(e=()=>Date.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||!Xt.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){!Xt.test(e)||!Array.isArray(t)||(this.candidates.delete(e),this.candidates.set(e,{pubkey:e,have:[...new Set(t.filter(s=>typeof s=="string"&&Xt.test(s)))].slice(-8),ticket:we(r)?r:null,at:this.clock()}),this.candidates.size>64&&this.candidates.delete(this.candidates.keys().next().value))}#n(e){return!!(e&&this.contexts.get(e.mediaType)===e)}holderMiss(e,t,r){if(!this.#n(e)||!Xt.test(t)||!Xt.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>=ga&&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.#n(e)&&e.holders.delete(t)}stale(e,t){let r=this.#n(e)?e.holders.get(t):null;return!!r&&r.misses>=fa&&this.clock()-r.firstMissAt>=pa}forget(e){for(let t of this.contexts.values())t.holders.delete(e)}spent(e){return e.spentAt!==null}rearm(e,t){if(!this.#n(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:xi,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 at(n,e,t){return new Promise((r,s)=>{let i=new AbortController,o=!1,a,l=(h,u,p=!1,g=u)=>{o||(o=!0,clearTimeout(a),e?.removeEventListener("abort",c),p&&i.abort(g),h?r(u):s(u))},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(h=>l(!0,h),h=>l(!1,h))})}var Si=24172,ma=24173,ya=24174,In=/^[0-9a-f]{64}$/u,ba="relayswarm-segment-v1",wa="relayswarm-segment-v2",va="relayswarm-segment-v3",Ei={1:ba,2:wa,3:va},xa=new TextEncoder,Sa=512,vt=new Map;function Ir(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=Kt(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):$t(e)?(vt.size>=Sa&&vt.delete(vt.keys().next().value),vt.set(r,!0),!0):!1}function Cr(n){return xa.encode(JSON.stringify(n)).length<=16*1024}function lt(n,e){let t=n.tags.filter(r=>r[0]===e);return t.length===1&&t[0].length===2?t[0][1]:null}function Cn(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 Ai(n){return n.v===3?3:n.v===2?2:1}function ki(n){let e=Ai(n),t=e>=2;return JSON.stringify({domain:Ei[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 Ea(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 Aa(n){return JSON.stringify({domain:"relayswarm-commitment-revocation-v1",v:1,streamEventId:n.streamEventId,swarmId:n.swarmId,delegationId:n.delegationId})}function Nr(n){try{return n.kind===30311&&Cr(n)&&Ir(n)&&typeof lt(n,"d")=="string"&&n.tags.some(e=>e.length===3&&e[0]==="relayswarm"&&e[1]==="redistribute"&&e[2]==="1")}catch{return!1}}function ka(n,{streamEvent:e,swarmId:t,revokedDelegationIds:r=[],delegationRevocations:s=[]},i=Date.now()){try{let o=Math.floor(i/1e3);if(!Nr(e)||!n||!Cr(n)||n.kind!==ma||n.pubkey!==e.pubkey||!Ir(n)||lt(n,"x")!==t||lt(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!==Ea(a)||a.domain!=="relayswarm-commitment-delegation-v1"||a.v!==1||a.streamEventId!==e.id||a.swarmId!==t||!In.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=>!(Cn(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||!Cr(l)||l.kind!==ya||l.pubkey!==e.pubkey||!Number.isSafeInteger(l.created_at)||l.created_ato+30||!Ir(l)||lt(l,"e")!==n.id||lt(l,"x")!==t)continue;let c=JSON.parse(l.content);if(l.content===Aa(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 _t(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))||!Cn(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||!Cn(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 Mi(n,{streamEvent:e,swarmId:t,key:r,context:s,maxSegmentBytes:i,delegation:o,revokedDelegationIds:a,delegationRevocations:l},c=Date.now()){try{let h=Math.floor(c/1e3);if(!Number.isSafeInteger(i)||i<1||i>16*1024*1024||!Nr(e)||!n||n.kind!==Si||!Cr(n)||!Number.isSafeInteger(n.created_at)||n.created_at>h+30||n.created_at=2;if(n.content!==ki(u)||u.domain!==Ei[p]||![1,2,3].includes(u.v)||u.streamEventId!==e.id||u.swarmId!==t||u.key!==r||u.sequence!==s.frag.sn||u.discontinuity!==(s.frag.cc??0)||u.part!==(s.part?.index??null)||!Number.isSafeInteger(u.sequence)||u.sequence<0||!Number.isSafeInteger(u.discontinuity)||u.discontinuity<0||u.part!==null&&(!Number.isSafeInteger(u.part)||u.part<0)||!In.test(u.sha256)||!Number.isSafeInteger(u.size)||u.size<1||u.size>i||!Number.isSafeInteger(u.expiresAt)||u.expiresAt<=h||u.expiresAt>h+300||p===3&&(u.pieceSize!==xt(u.size)||!Array.isArray(u.pieces)||u.pieces.length!==Math.ceil(u.size/u.pieceSize)||u.pieces.some(f=>typeof f!="string"||!In.test(f))))return null;if(g){let f=_t(s);if(!f||u.rendition!==f.playlist||u.playlist!==f.playlist||u.mediaType!==f.mediaType||JSON.stringify(u.encryption)!==JSON.stringify(f.encryption))return null}else if(u.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=ka(o,{streamEvent:e,swarmId:t,revokedDelegationIds:a,delegationRevocations:l},c);if(!f||n.pubkey!==f.delegatePubkey||lt(n,"delegation")!==o.id||n.created_atf.expiresAt||!f.renditions.includes(u.rendition)||!f.mediaTypes.includes(g?u.mediaType:"main")||u.part!==null&&!f.allowParts||u.size>f.maxSegmentBytes)return null}return u}catch{return null}}var Bi=new TextEncoder,Ma=new TextDecoder;function Ri(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 Ba=(n,e)=>new Uint8Array(n.memory.buffer,n.rs_result_ptr(),e);function Ti(n,{size:e,sha256:t,pieces:r,deadline:s,maxHolders:i,originReserveMs:o,peerOnly:a=!1},l,c){if(l()||!Ra.every(h=>typeof n[h]=="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 h=Ri(n,Bi.encode(JSON.stringify({sha256:t,pieces:r,...a?{peerOnly:!0}:{}})),(u,p)=>n.rs_xfer_new(e,s,i,o,u,p));return h?new Pn(n,h,l,c,a):null}catch(h){return c(h),null}}var Ra=["rs_xfer_new","rs_xfer_call","rs_xfer_free"],Jt={start:0,delivered:1,failed:2,tick:3,state:4,progress:5},Pn=class{#n;#t;#e;#s;#d;constructor(e,t,r,s,i=!1){this.#n=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.#n.rs_xfer_capabilities=="function"&&!!(this.#n.rs_xfer_capabilities()&1)}catch{}let l=new Set(o),c=a?t:t.filter(([h])=>!l.has(h));return this.#i(Jt.start,e,-1,0,0,Bi.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(Jt.delivered,e,t,r.start,r.end,s)}failed(e,t){return this.#i(Jt.failed,e,t,0,0,Nn)}tick(e){return this.#i(Jt.tick,e,-1,0,0,Nn)}progress(e,t,r){return this.#i(Jt.progress,e,t,r,0,Nn)}free(){if(this.#t===null)return;let e=this.#t;if(this.#t=null,!this.#e())try{this.#n.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.#n;try{let l=Ri(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=Ba(a,l),h=new DataView(c.buffer,c.byteOffset,l).getUint32(0,!0),u=JSON.parse(Ma.decode(c.subarray(4,4+h))),p=l>4+h?c.slice(4+h):null;return{commands:u.c.map(f=>f.p?{...f,range:{start:f.p[0],end:f.p[1]}}:f),next:u.next,late:u.late,finished:u.finished,verified:u.verified??null,bytes:p}}catch(l){return this.#s(l),null}}},Nn=new Uint8Array(0);var Me={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},Ue={sendText:1,sendBinary:2,closed:3,report:4,resolved:5,haveChanged:6,scheduleChanged:7,serveRequest:8,uploadCancelled:9,progress:10,serveRange:11},Ta=128*1024,La=32*1024,_a=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"]),ct=new TextEncoder,Ot=new TextDecoder,Hn=new Uint8Array(0),Dn=()=>{try{return globalThis.performance.now()}catch{return null}},Li=n=>{let e=Math.trunc(Math.max(1,n));return e>=1&&e<=2**31-1?e:1},Pr=class n{get supportsRanges(){return!this.closed}static ABANDON_REASON=ot.ABANDON_REASON;#n;#t;#e=-1;#s=null;#d=null;#i=0;#c=!1;#o=!1;#r=new Map;#h=null;#k=!1;#M=0;constructor({pubkey:e,pc:t,channel:r,maxSegmentBytes:s,onRequest:i,onHaveChange:o,onScheduleChange:a,onClose:l,onUploadCancelled:c,maxQueuedRequests:h=4,drainTimeoutMs:u=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=h,this.drainTimeoutMs=u,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.#n=p,this.#i=this.openedAt,this.#t=p.newLink(s,h,u,this.#l(),this.openedAt),p.links.add(this),r.binaryType="arraybuffer",r.bufferedAmountLowThreshold=La,r.addEventListener("message",g=>{if(this.closed)return;let{data:f}=g;typeof f=="string"?this.#a(Me.text,{bytes:ct.encode(f)}):this.#a(Me.binary,{bytes:f instanceof ArrayBuffer?new Uint8Array(f):ArrayBuffer.isView(f)?new Uint8Array(f.buffer,f.byteOffset,f.byteLength):Hn})}),r.addEventListener("close",()=>this.close("channel-close")),r.addEventListener("error",()=>this.close("channel-error")),r.addEventListener("bufferedamountlow",()=>{this.closed||this.#a(Me.bufferedLow,{a:this.#B()})}),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(Me.sendHave,{bytes:ct.encode(JSON.stringify([...e]))})}sendHaveChange(e=[],t=[]){this.closed||this.#a(Me.sendHaveChange,{bytes:ct.encode(JSON.stringify({add:[...e],del:[...t]}))})}sendContribution(e,t){this.closed||this.#a(Me.sendContribution,{a:e?1:0,bytes:ct.encode(JSON.stringify(typeof t=="string"?t:null))})}sendFetching(e,t=0){this.closed||this.#a(Me.sendFetching,{a:t,bytes:ct.encode(String(e))})}request(e,t,{signal:r,expectedSize:s,onResult:i,onProgress:o,range:a}={}){let l=Dn(),c=!1,h=(p,g=null)=>{if(!c&&(c=!0,typeof i=="function"))try{let f=null;if(Number.isFinite(l)){let v=Dn();Number.isFinite(v)&&(f=v-l)}let m=g?.receivedBytes??0,y=Number.isFinite(u?.firstByteAt)&&Number.isFinite(l)?u.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(y)&&y>=0?y:null,metadataReceived:g?.metadataReceived===!0,draining:g?.draining===!0,closeReason:_a.has(this.closeReason)?this.closeReason:null})}catch{}},u=null;if(this.closed||this.#c||r?.aborted){let p=Promise.resolve(null);return h(this.closed?"closed":this.#c?"busy":"abort"),p}return new Promise(p=>{let g=()=>{u.id!==null&&!this.closed&&this.#a(Me.abort,{a:u.id,b:r?.reason===n.ABANDON_REASON?1:0})};u={id:null,firstByteAt:null,settled:!1,report:h,onProgress:o,startedAt:l,settle:m=>{u.settled||(u.settled=!0,r?.removeEventListener("abort",g),p(m))}};let f=s===void 0?NaN:Number.isSafeInteger(s)&&s>=0?s:-1;this.#h=u;try{a?this.#a(Me.requestRange,{a:Li(t),b:a.objectSize,bytes:ct.encode(JSON.stringify([String(e),a.start,a.end]))}):this.#a(Me.request,{a:Li(t),b:f,bytes:ct.encode(String(e))})}finally{this.#h=null}if(u.id===null){u.settle(null),h("closed");return}u.settled||r?.addEventListener("abort",g,{once:!0})})}close(e="host"){if(!this.closed){if(this.#t===null)return this.#b("host");this.#a(Me.close,{bytes:ct.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.#n.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.#r.values())t.settle(null),t.report("closed");this.#r.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=Hn,now:i=this.#f()}={}){if(this.#t===null)return;let o=this.#n.call(this.#t,e,i,(this.#S()?1:0)|(this.#l()?2:0),t,r,s);o&&this.#A(o)}#A({header:e,events:t}){let[r,s,i,o,a,l,c,h,u,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=h,this.lastServedAt=u,this.lastDeliveredAt=p,!Number.isNaN(f)&&this.#h&&(this.#h.id=f,this.#r.set(f,this.#h)),r!==this.#e&&this.#w(r),this.closed&&this.announced.clear();let y=++this.#M;for(let v of t)this.#O(v);if(y===this.#M&&this.#t!==null&&(this.#Y(g),m===1&&this.#B()<=Ta))return this.#a(Me.bufferedLow,{a:this.#B()});this.closed&&!this.#o&&this.#t!==null&&(this.#n.free(this.#t),this.#t=null,this.#n.links.delete(this),this.#I())}#w(e){let t=this.#n.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 Ue.sendText:{if(this.#k)return;let i=Ot.decode(t);try{this.channel.send(i)}catch{this.#k=!0,this.close("send-error")}return}case Ue.sendBinary:{if(this.#k)return;try{this.channel.send(t)}catch{this.#k=!0,this.close("serve-error")}return}case Ue.closed:{this.closeReason=Ot.decode(t),this.#I();try{this.channel.close()}catch{}try{this.pc.close()}catch{}this.onClose?.(this);return}case Ue.report:{let i=JSON.parse(Ot.decode(t)),o=i.id===null?this.#h:this.#r.get(i.id);if(!o)return;o.report(i.outcome,i),o.settled&&i.id!==null&&this.#r.delete(i.id);return}case Ue.resolved:{let i=Number.isNaN(r)?this.#h:this.#r.get(r);if(!i)return;i.settle(t);return}case Ue.haveChanged:{let i=JSON.parse(Ot.decode(t));this.onHaveChange?.(this,i);return}case Ue.scheduleChanged:{this.onScheduleChange?.(this);return}case Ue.serveRequest:case Ue.serveRange:{let i,o;if(e===Ue.serveRange){let[a,l,c]=JSON.parse(Ot.decode(t));i=a,o={start:l,end:c}}else i=Ot.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 Ue.uploadCancelled:{this.onUploadCancelled?.(this,s(0));return}case Ue.progress:{let i=s(0),o=s(1);for(let a of this.#r.values())if(!a.settled&&(a.firstByteAt===null&&(a.firstByteAt=Dn()),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}.`)}}#B(){try{return Math.max(0,Number(this.channel.bufferedAmount)||0)}catch{return 0}}#v(e,t){if(this.#t===null)return;let r=this.#B(),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(Me.serve,{a:0,b:r});if(s&&t&&this.#n.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(Me.serve,{a:0,b:r}):this.#a(Me.serveRange,{a:i,b:r,bytes:s.subarray(t.start*o,Math.min(i,t.end*o))})}this.#a(Me.serve,{a:s?1:0,b:r,bytes:s??Hn})}#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(Me.tick)},Math.max(0,e-this.#f())))}#I(){this.#s!==null&&globalThis.clearTimeout(this.#s),this.#s=null,this.#d=null}};var Oa=/^[0-9a-f]{64}$/u,oe={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},Ia=6e4,Ca=2e4,Na=new Set([oe.stale,oe.current,oe.valid,oe.live,oe.reserved,oe.suppresses]),Qt=class extends Error{constructor(e){super("Core discovery failed.",{cause:e})}},Hr=class{#n;#t;#e=null;#s=new Map;#d=new Map;#i=new WeakMap;#c=null;#o=null;#r=new WeakMap;#h=new WeakMap;#k=new Map;#M=1;#b=null;#S=null;constructor(e,t,r=()=>Date.now()){this.#n=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(oe.candidates,[]).map(e=>[e.pubkey,e]))}retire(){this.#e||(this.#S=null,this.#e=new Lt(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 Qt))throw r;this.retire();try{this.#t?.(r.cause)}catch{}return t(this.#e)}}#f(e,t){try{let r=this.#n(e,this.clock(),t);if(e===oe.candidates)return r.map(([s,i,o,a])=>({pubkey:s,have:i,ticket:o,at:a}));if(Na.has(e)&&typeof r!="boolean")throw new TypeError(`Core discovery answered operation ${e} with ${typeof r}.`);return r}catch(r){throw new Qt(r)}}#a(e,t){try{let{r,s}=this.#n(e,this.clock(),t);return this.#A(s),r}catch(r){throw new Qt(r)}}#A({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.#r.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.#r.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.#k:this.#h,i=s.get(e);return i===void 0&&t&&s.set(e,i=this.#M++),i}#B(e){let t=this.clock();return this.#S??=this.#f(oe.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(oe.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(oe.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"||!Oa.test(e)||!Array.isArray(t)||this.#l(()=>{this.#S=null,this.#f(oe.hint,[e,t.filter(s=>typeof s=="string"),we(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(oe.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(oe.holderAhead,[this.#w(e),t])},r=>r.holderAhead(e,t))}stale(e,t){return typeof t!="string"?!1:this.#l(()=>this.#f(oe.stale,[this.#w(e),t]),r=>r.stale(e,t))}forget(e){typeof e=="string"&&this.#l(()=>{this.#f(oe.forget,[e])},t=>t.forget(e))}current(e){return this.#l(()=>this.#w(e)!==null&&this.#f(oe.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(oe.current,[this.#w(o)])&&t(o)).map(o=>o.mediaType);return i.length===0?this.#b=null:this.#v(this.#a(oe.choose,[this.#B(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(oe.hinted,[r,this.#B(t)]))},r=>r.hinted(e,t))}begin(e){return this.#l(()=>!e||e!==this.#b?null:(this.#b=null,this.#a(oe.begin,[])===null?null:this.#c?.attempt??null),t=>t.begin(e))}valid(e){return this.#l(()=>{let t=e?this.#r.get(e):void 0;return t!==void 0&&this.#f(oe.valid,[t])},t=>t.valid(e))}replaced(e,t){return this.#l(()=>{let r=e?this.#r.get(e):void 0;return r!==void 0&&this.#a(oe.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.#r.get(e);r!==void 0&&this.#a(oe.allocated,[r,this.#O(t,!0)])},r=>r.allocated(e,t))}abandoned(e){this.#l(()=>{let t=e?this.#r.get(e):void 0;t!==void 0&&this.#a(oe.abandoned,[t])},t=>t.abandoned(e))}failed(e){this.#l(()=>{let t=this.#O(e,!1);t!==void 0&&this.#a(oe.failed,[t])},t=>t.failed(e))}end(e=this.window){return this.#l(()=>!!e&&e===this.#c&&this.#a(oe.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(oe.verified,[t])},t=>t.verified(e))}live(e=this.window){return this.#l(()=>!!e&&e===this.#c&&this.#f(oe.live,[]),t=>t.live(e))}reserved(){return this.#l(()=>this.#f(oe.reserved,[]),e=>e.reserved())}suppresses(e){return typeof e!="string"?!1:this.#l(()=>this.#f(oe.suppresses,[e]),t=>t.suppresses(e))}snapshot(){return this.#l(()=>({...this.#f(oe.snapshot,[]),counters:{...this.counters}}),e=>e.snapshot())}clear(){this.#l(()=>{this.#b=null,this.#S=null,this.#a(oe.clear,[])},e=>e.clear())}};var Pa=0,Ha=1,Da=2,Ua=3,_i=new TextEncoder,Un=new TextDecoder;function za(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:_t(n)}}async function qa(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 Fa=["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"],Oi=13,ja=15,zn=13,Ci=zn*8,Wa=5,It=n=>Number.isNaN(n)?null:n,Ii=(n,e)=>new Float64Array(n.memory.buffer,e,6);function Dr(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 Ur=(n,e)=>new Uint8Array(n.memory.buffer,n.rs_result_ptr(),e);function Ka(n,e){let t=Ur(n,e),r=new DataView(t.buffer,t.byteOffset,e),s=new Array(zn);for(let o=0;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 qn=class{#n;#t;#e=null;#s=new WeakMap;#d=0;constructor(e,t){this.#n=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.#n)}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=>Ii(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 It(this.#o(0))}rate(){return It(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=>It(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=>It(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]=Ii(t,t.rs_sel_summary(this.#c(e)));return{attempts:r,latencyMs:It(s),throughputBytesPerSecond:It(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(u=>!u.closed&&!u.busy&&!r.has(u.pubkey)&&u.have.has(t)),l=a.map(u=>this.#c(u)),c=l.length*4,h=o.rs_alloc(c);try{let u=new DataView(o.memory.buffer,h,c);l.forEach((g,f)=>u.setUint32(f*4,g,!0));let p=o.rs_sel_select(h,l.length,s,i);return p<0?null:a[l.indexOf(p)]}finally{o.rs_free(h,c)}},o=>o.select(e,t,r,s,i))}};async function Ni(n,{onFailure:e}={}){let{instance:t,module:r}=await qa(n),s=t.exports;for(let m of["memory","rs_alloc","rs_free","rs_call","rs_result_ptr",...Fa])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[...h.links])m.die()}},c=m=>{if(!i){l();try{e?.(m)}catch{}}},h={links:new Set,rangeUploads:typeof s.rs_link_serve_range=="function",newLink(m,y,v,b,T){if(i)throw new Error("The core has been retired.");return s.rs_link_new(m,y,v,b?1:0,T)},free(m){if(!i)try{s.rs_link_free(m)}catch(y){c(y)}},call(m,y,v,b,T,B,$){if(i)return null;try{let S=Dr(s,$,(L,U)=>y===ja&&h.rangeUploads?s.rs_link_serve_range(m,v,b,T,B,L,U):s.rs_link_call(m,y,v,b,T,B,L,U));if(S<0||Ss.rs_link_call(m,Oi,0,0,0,0,v,b));if(y<0)throw new Error(`Core link ${m} refused operation ${Oi}.`);return JSON.parse(Un.decode(Ur(s,y)))}catch(y){return c(y),null}}};function u(m,y){let v;try{v=_i.encode(JSON.stringify(y))}catch{return null}let b=Dr(s,v,(T,B)=>s.rs_call(m,T,B));return b<0?null:JSON.parse(Un.decode(Ur(s,b)))}function p(m,y,v){if(i)throw new Error("The core has been retired.");let b=_i.encode(JSON.stringify(v)),T=Dr(s,b,(B,$)=>s.rs_disc_call(m,y,B,$));if(T<0)throw new Error(`Core discovery refused operation ${m}.`);return JSON.parse(Un.decode(Ur(s,T)))}let g=({streamEvent:m,swarmId:y,revokedDelegationIds:v=[],delegationRevocations:b=[]})=>({streamEvent:m,swarmId:y,revokedDelegationIds:v,delegationRevocations:b}),f=Object.freeze({kind:"wasm",validStreamAuthorisation:m=>u(Pa,[m])===!0,verifyCommitmentDelegation:(m,y,v=Date.now())=>u(Ha,[m??null,g(y),v]),verifySegmentCommitment(m,y,v=Date.now()){let b;try{b=za(y.context)}catch{return null}return u(Da,[m??null,{...g(y),key:y.key,context:b,maxSegmentBytes:y.maxSegmentBytes,delegation:y.delegation??null},v])}});return Object.freeze({module:r,verifier:f,playerHint(m){if(i)return null;try{return u(Ua,m)}catch(y){return c(y),null}},retire:l,get retired(){return i},peerSelection(){if(o)throw new Error("This core instance already has a peer selection.");return o=new qn(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 Hr(p,c,m)},peerLink(m){return new Pr(m,h)},transfer(m){return Ti(s,m,()=>i,c)}})}var Va=new Uint8Array(0);var $a=Object.freeze({maxTransfers:2,maxSegmentBytes:16777216,maxActiveBytes:33554432,maxPending:32,maxPendingBytes:33554432,initTimeoutMs:5e3,operationTimeoutMs:5e3}),Ga=Object.freeze({maxTransfers:4,maxSegmentBytes:32*1048576,maxActiveBytes:64*1048576,maxPending:128,maxPendingBytes:64*1048576,initTimeoutMs:3e4,operationTimeoutMs:3e4}),Pi=n=>typeof n=="string"&&n.length===64&&/^[a-f0-9]{64}$/.test(n),je=n=>Number.isSafeInteger(n)&&n>=0,tr=n=>Number.isFinite(n)&&n>=0&&n<=Number.MAX_SAFE_INTEGER,er=n=>n===null||tr(n),Ya=(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||tr(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}},Ct=()=>new DOMException("Core transfer was cancelled.","AbortError");function Za(n={}){let e={};for(let[t,r]of Object.entries($a)){let s=n[t]??r;if(!Number.isSafeInteger(s)||s<1||s>Ga[t])throw new fe("invalid-limits");e[t]=s}return Object.freeze(e)}function Xa(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||!Pi(t.sha256)||!Array.isArray(t.pieces)||t.pieces.length<1||t.pieces.length>256||!t.pieces.every(Pi)||!tr(t.deadline)||!je(t.maxHolders)||t.maxHolders<1||t.maxHolders>32||!tr(t.originReserveMs)||n.peerOnly!==void 0&&typeof n.peerOnly!="boolean")throw new fe("invalid-transfer");return t}function Ja(n,e,t,r=!1){let[s,i,o]=e;if(!tr(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])&&er(l[1])&&er(l[2]))||(r?a.origin!=null:!Array.isArray(a.origin)||a.origin.length!==2||!a.origin.every(er))||!er(a.sharedFirstByteMs??null)||!er(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??((L,U)=>new Worker(L,U)),l;try{l=a(e,{type:"module",name:"relayswarm-transfer"})}catch{throw new fe("worker-unavailable")}let c="loading",h=null,u=0,p=0,g=0,f=0,m=new Map,y=new Map,v=L=>{L.signal?.removeEventListener("abort",L.onAbort),y.get(L.id)===L&&(y.delete(L.id),f-=L.size)},b=(L,U=!0)=>{if(!(c==="stopped"||c==="failed")){c=U?"failed":"stopped",h=L.code??L.name,l.removeEventListener("message",$),l.removeEventListener("error",T),l.removeEventListener("messageerror",T),r?.removeEventListener("abort",B);for(let C of m.values())clearTimeout(C.timer),C.settled||C.reject(L);m.clear(),g=0;for(let C of y.values())C.closed=!0,v(C);try{l.terminate()?.catch?.(()=>{})}catch{}if(U)try{s?.(L)?.catch?.(()=>{})}catch{}}},T=L=>{L?.preventDefault?.(),b(new fe("worker-error"))},B=()=>b(Ct(),!1),$=({data:L})=>{if(!L||L.v!==1||!je(L.id)||!m.has(L.id))return;let U=m.get(L.id);if(m.delete(L.id),g-=U.bytes,clearTimeout(U.timer),L.ok!==!0){let C=new fe(typeof L.error=="string"&&/^[a-z-]{1,40}$/.test(L.error)?L.error:"invalid-response");U.settled||U.reject(C),(L.fatal||L.ok!==!1)&&b(C)}else if(["init","new","free"].includes(U.op)?L.result!==!0:!Ya(L.result,U.size)){let C=new fe("invalid-response");U.settled||U.reject(C),b(C)}else U.settled||U.resolve(L.result)},S=(L,U,C,F=0,O=[],d=!1)=>c==="stopped"||c==="failed"?Promise.reject(new fe("closed")):!d&&m.size>=o.maxPending||g+F>o.maxPendingBytes?Promise.reject(new fe("queue-limit")):new Promise((w,A)=>{let x=++u,R={resolve:w,reject:A,handle:U,bytes:F,op:L,size:y.get(U)?.size??o.maxSegmentBytes,settled:!1,timer:setTimeout(()=>b(new fe(L==="init"?"init-timeout":"operation-timeout")),L==="init"?o.initTimeoutMs:o.operationTimeoutMs)};m.set(x,R),g+=F;try{l.postMessage({v:1,id:x,op:L,handle:U,input:C},O)}catch{b(new fe("worker-message"))}});l.addEventListener("message",$),l.addEventListener("error",T),l.addEventListener("messageerror",T),r?.addEventListener("abort",B,{once:!0}),r?.aborted&&B();try{await S("init",null,{module:n,limits:o})}catch(L){throw b(L),L}if(c!=="loading")throw new fe("closed");return c="ready",Object.freeze({snapshot:()=>({state:c,reason:h,transfers:y.size,activeBytes:f,pending:m.size,pendingBytes:g}),stop:B,async transfer(L,{signal:U}={}){if(c!=="ready")throw new fe("closed");if(U?.aborted)throw Ct();let C=Xa(L,o);if(y.size>=o.maxTransfers||f+C.size>o.maxActiveBytes)throw new fe("transfer-limit");let F={id:++p,size:C.size,closed:!1,signal:U,release:null};y.set(F.id,F),f+=C.size;let O=()=>{if(F.release)return F.release;F.closed=!0;for(let w of m.values())w.handle===F.id&&!w.settled&&(w.settled=!0,w.reject(Ct()));return F.release=S("free",F.id,null,0,[],!0).then(()=>!0,()=>!1).finally(()=>v(F))};F.onAbort=()=>{O()},U?.addEventListener("abort",F.onAbort,{once:!0});try{await S("new",F.id,C)}catch(w){throw F.closed||v(F),w}if(F.closed||U?.aborted)throw O(),Ct();let d=async(w,A)=>{if(F.closed)throw new fe("closed-transfer");try{let x=Ja(w,A,o.maxSegmentBytes,C.peerOnly===!0),R=0,P=[];if(w==="delivered"){if(R=x[3].byteLength,g+R>o.maxPendingBytes)throw new fe("queue-limit");x[3]=x[3].slice(),P=[x[3].buffer]}let N=await S(w,F.id,x,R,P);if(F.closed)throw Ct();return N}catch(x){throw O(),x}};return Object.freeze({start:(w,A)=>d("start",[w,A]),delivered:(w,A,x,R)=>d("delivered",[w,A,x,R]),failed:(w,A)=>d("failed",[w,A]),progress:(w,A,x)=>d("progress",[w,A,x]),tick:w=>d("tick",[w]),free:O,cancel:O,get closed(){return F.closed}})}})}function Di(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 ht(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 Ui(n,e,t,r,{signal:s,onIgnored:i,onResult:o}={}){let a=Di(e,t,r);return!a||typeof n?.Loader!="function"||typeof e?.url!="string"||s?.aborted?(ht(o,s?.aborted?"abort":"invalid-request",t,r),Promise.resolve(null)):new Promise(l=>{let c=null,h=!1,u=(f,m,y=f?.byteLength??null,v=null)=>{if(!h){h=!0,s?.removeEventListener("abort",p);try{c?.destroy?.()}catch{}ht(o,m,t,r,y,v),l(f)}},p=()=>{try{c?.abort?.()}catch{}u(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 u(null,"abort");let m=g(f?.data);if(!m&&!h)try{i?.()}catch{}u(m,m?"payload":"wrong-size",f?.data?.byteLength??null,f?.code)},onError:f=>u(null,s?.aborted?"abort":"error",null,f?.code),onTimeout:()=>u(null,s?.aborted?"abort":"timeout"),onAbort:()=>u(null,"abort")})}catch{u(null,"exception")}})}function Qa(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 zi(n,e,t,{signal:r,onIgnored:s,onResult:i,fetchImpl:o=globalThis.fetch}={}){let a=Di(n,e,t);if(!a||typeof n?.url!="string"||typeof o!="function"||r?.aborted)return ht(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 ht(i,r?.aborted?"abort":"error",e,t),null}let c=(h=null)=>{try{s?.()}catch{}return ht(i,"wrong-size",e,t,h,l.status),null};try{if(l.status!==206||!Qa(l.headers.get("content-range"),a)){try{await l.body?.cancel()}catch{}return l.status===200||l.status===206?c():(ht(i,"error",e,t,null,l.status),null)}let h=new Uint8Array(await l.arrayBuffer());return h.byteLength!==t-e?c(h.byteLength):(ht(i,"payload",e,t,h.byteLength,l.status),h)}catch{return ht(i,r?.aborted?"abort":"error",e,t,null,l?.status),null}}var Te=Symbol("relayswarm-warm-ahead"),We=24*1024*1024,qi=3,Fn=4,rr=8e3,el=100,dt=n=>{let{start:e,duration:t}=n?.context?.frag??{};return Number.isFinite(e)&&e>=0&&Number.isFinite(t)&&t>0&&Number.isFinite(e+t)},jn=(n,e)=>dt(n)&&n.context.frag.start<=e&&en?.key===e?.key&&n?.scope===e?.scope&&dt(n)&&dt(e)&&n.context.frag.start===e.context.frag.start&&n.context.frag.duration===e.context.frag.duration,tl=(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 Fi({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:h=null,startupCommit:u=null,startupRecovery:p=()=>2e3}){let g=!1,f=0,m=null,y=null,v=[],b,T,B=null,$=0,S=new Map,L=new Set,U=new Map,C=new Set,F=new Set,O=new Map,d={enabled:typeof h=="function",state:h?"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},w={started:0,verified:0,rejected:0,cancelled:0,coalesced:0,promotions:0,localReuseBytes:0,verifiedBytes:0,verifiedPeerBytes:0,consumedPeerBytes:0,cacheBytes:0,highWaterBytes:0},A=()=>d.reserved+[...U.values()].reduce((E,k)=>E+k.reserved,0),x=()=>new Set([...S.keys(),...U.keys(),...d.owner?[d.own.key]:[]]).size,R=()=>d.state==="buffering"?Fn:qi,P=E=>U.get(E.key)===E&&!E.finished,N=E=>{let k=S.get(E);k&&(w.cacheBytes-=k.data.byteLength,S.delete(E))},M=(E,k)=>{P(E)&&(E.finished=!0,U.delete(E.key),C.delete(E),m===E&&(m=null),E.reserved=0,E.finish(k),d.checking&&(d.recheck=!0),W(),queueMicrotask(q))},H=E=>{P(E)&&(w.cancelled++,E.cancel(),M(E,null))},D=()=>{(d.state==="idle"||d.state==="buffering")&&Q("cancelled","cleared",!g),d.planningServiceMs=null,f++,v=[],B=null;for(let E of[...U.values()])H(E);for(let E of S.keys())N(E);for(let E of[...F])E(!0)},q=()=>{if(g||m||!l()||!v.length||L.size+C.size>1||!c&&d.state!=="buffering"||d.state==="buffering"&&(!d.permit||d.checking)||d.state==="buffering"&&!jr()||d.state==="buffering"&&x()>=R())return;let E=v.shift();if(S.has(E.key)||U.has(E.key)){queueMicrotask(q);return}for(;x()>=qi&&S.size&&d.state!=="buffering";)N(S.keys().next().value);if(x()>=R())return;let k=new AbortController,z=f,Z=b,_=T,K,J,X,G={...E,reserved:0,finished:!1,waiters:new Set,genuineAt:null,promise:new Promise(te=>{X=te}),noteDemand(){G.genuineAt??=performance.now(),E.context[Te]?.onGenuine?.()},genuine(){if(!P(G))return null;let te=[...G.waiters].find(xe=>xe.pendingTerminal&&Ae(xe.context)?.key===G.key);return te&&G.genuineAt!==null?{at:G.genuineAt,context:te.context}:null},promote(){clearTimeout(J)},finish:te=>X(te),cancel(){k.abort(),clearTimeout(J);try{K?.abort(),K?.destroy()}catch{}}};m=G,U.set(G.key,G),J=setTimeout(()=>H(G),rr),(async()=>{try{let te=await t(E.context,k.signal);if(k.signal.aborted||g||z!==f||!P(G)||!l())return null;if(!te||!Number.isSafeInteger(te.size)||te.size<1||te.size>We)return w.rejected++,null;for(;w.cacheBytes+A()+te.size>We&&S.size&&d.state!=="buffering";)N(S.keys().next().value);if(w.cacheBytes+A()+te.size>We)return w.rejected++,null;if(G.reserved=te.size,!s(A()))return G.reserved=0,w.rejected++,null;w.highWaterBytes=Math.max(w.highWaterBytes,w.cacheBytes+A());let xe=E.context[Te]={peerBytes:0,genuine:()=>G.genuine(),startupDependency:()=>{if(!j()||!P(G)||!l()||!pe(E))return null;try{return me()===null||!j()?null:{at:d.entryAt,deadline:d.deadline,signal:d.controller.signal,context:E.context}}catch{return null}}};K=new n(Z),w.started++;let ue=performance.now(),he=await new Promise(le=>K.load(E.context,_,{onSuccess:(be,ce,Pe,Ce)=>le({response:be,stats:ce,details:Ce,serviceMs:tl(ce,te.size,ue,performance.now())}),onError:(...be)=>le({failure:{name:"onError",args:be,stats:K.stats}}),onTimeout:(...be)=>le({failure:{name:"onTimeout",args:be,stats:K.stats}}),onAbort:(...be)=>le({failure:{name:"onAbort",args:be,stats:K.stats}}),onProgress:be=>{if(be?.loaded>te.size){k.abort();try{K.abort()}catch{}le(null)}}}));if(he?.failure)return k.signal.aborted||g||z!==f||!P(G)?null:(w.rejected++,he);if(!he||k.signal.aborted||g||z!==f||!P(G)||!await r(te,he.response.data,E.context,k.signal))return w.rejected++,null;if(k.signal.aborted||g||z!==f||!P(G))return null;let de=he.response.data;if(de.byteLength!==te.size)return w.rejected++,null;if(G.reserved=0,i?.(te,de,E.context)===!1)return null;let ye={...he,context:E.context,scope:E.scope,data:de,permit:te,peerBytes:xe.peerBytes,accept:xe.accept};return S.set(E.key,ye),w.cacheBytes+=de.byteLength,w.verified++,w.verifiedBytes+=de.byteLength,w.verifiedPeerBytes+=xe.peerBytes,j()&&P(G)&&f===z&&E.scope===y&&pe(E)&&(d.planningServiceMs=he.serviceMs),ye}catch{return k.signal.aborted||w.rejected++,null}finally{clearTimeout(J);try{K?.destroy()}catch{}}})().then(te=>M(G,te))},ee=(E,k,z,Z)=>{B=null;let _=Ae(E);if(!_||g)return null;y!==_.scope&&(y!==null&&D(),y=_.scope),b=k,T=z;let K=[];try{K=e(E).map(Ae).filter(Boolean).filter(X=>X.scope===y).slice(0,2)}catch{}let J=new Set([_.key,...K.map(X=>X.key)]);for(let X of S.keys())J.has(X)||N(X);for(let X of[...U.values()])J.has(X.key)||H(X);return v=K,dt(_)&&K.every(dt)&&(B={own:ae(_),upcoming:K.map(ae),owner:Z}),_},j=()=>{if(d.state!=="buffering"||g||d.revision!==f||d.owner?.pendingTerminal!==d.terminal||d.terminal.settled)return!1;let E=!1;try{E=ut(Ae(d.terminal.context),d.identity)&&ut(Ae(d.own.context),d.identity)&&d.terminal.context.url===d.contextUrl&&d.terminal.context.frag.url===d.fragUrl}catch{}return E?!0:(Q("cancelled","context-changed"),!1)},V=E=>({code:0,text:"RelaySwarm startup buffer unavailable",startupBufferReason:E}),re=E=>e(E.context).map(Ae).filter(Boolean).filter(k=>k.scope===y&&dt(k)).slice(0,2),ae=E=>{let{key:k,scope:z,context:{url:Z,frag:_}}=Ae(E.context);return{key:k,scope:z,context:{url:Z,frag:_,part:null,responseType:"arraybuffer"}}},ge=(E,k)=>({...ae(E),identity:ae(E),parent:ae(k)}),ne=E=>{try{return ut(Ae(E.context),E.identity)&&re(E.parent).some(k=>ut(k,E.identity))}catch{return!1}},pe=E=>{if(!j()||B?.owner!==d.terminal.id)return!1;let k=d.plan.find(z=>ut(z.identity,E));return!!(k&&ne(k))},Q=(E,k,z=!0)=>{if(!["idle","buffering"].includes(d.state))return;let Z=d.owner,_=d.terminal;d.state=E,d.reason=k,E==="failed"&&d.failures++,E==="cancelled"&&d.cancellations++,clearTimeout(d.timer),d.timer=null,clearTimeout(d.poll),d.poll=null,d.controller?.abort(),d.releasePins?.(),d.owner=null,d.terminal=null,d.response=null,d.reserved=0,v=[],d.plan=[],d.cursor=null,d.frozenStart=null,d.planningServiceMs=null;for(let K of[...U.values()])H(K);for(let K of S.keys())N(K);if(!(!Z||!_||_.settled||Z.pendingTerminal!==_)){_.settled=!0,Z.pendingTerminal=null,Z.token++,Z.stats.aborted=!0;try{Z.inner.abort()}catch{}!z||g||(E==="cancelled"?_.callbacks.onAbort?.(Z.stats,_.context,null):_.callbacks.onError?.(V(k),_.context,null,Z.stats))}},me=()=>{let E;try{E=h()}catch{return Q("failed","target-threw"),null}return E===null?(Q("cancelled","target-unavailable"),null):!Number.isFinite(E)||E<0?(Q("failed","invalid-target"),null):(d.targetTime=E,E)},et=()=>{let E;try{E=p(d.own.context)}catch{}return!Number.isFinite(E)||E<0?(Q("failed","invalid-recovery"),null):(d.requiredHeadroomMs=E,E)},Ie=(E,k)=>{if(!j()||d.checking)return;if(d.frozenStart!==null&&E>=d.frozenStart&&(d.frozenStart=null),d.plan.some(_=>!ne(_))||d.cursor&&!ne(d.cursor))return Q("cancelled","context-changed");for(;d.plan.length;){let _=d.plan[0],K=S.get(_.key),J=U.get(_.key);if(_.context.frag.start+_.context.frag.duration>E||J||K&&O.has(K.permit.key)||[...L].some(X=>X.pendingTerminal&&Ae(X.context)?.key===_.key))break;if(!K){if(!d.hopAvailable)return;d.hopAvailable=!1}if(d.cursor=_,d.plan.shift(),v=v.filter(X=>X.key!==_.key),!j()||d.checking)return;N(_.key)}let z=d.plan[0];if(d.verified&&d.response&&d.plan.length===2&&S.size===2&&!m&&!U.size&&!L.size&&!C.size&&jn(z,E)&&d.plan.every(_=>S.has(_.key)&&!O.has(S.get(_.key).permit.key))){let _=St(E);_.end!==null&&(_.end-E)*1e3S.has(_.key)&&!O.has(S.get(_.key).permit.key))){let _=St(E);_.rows.length===d.plan.length+1&&_.end!==null&&(_.end-E)*1e3_.context.frag.start)?d.cursor:_??d.own,J;try{J=re(K)[0]}catch{return Q("cancelled","context-changed")}if(!J)return;let X=K.context.frag.start+K.context.frag.duration;if(Math.abs(J.context.frag.start-X)>.001||J.key===d.own.key||d.plan.some(te=>te.key===J.key))return Q("cancelled","context-changed");let G=ge(J,K);if(J.context.frag.start+J.context.frag.duration<=E){if(!d.hopAvailable)return;d.hopAvailable=!1,d.cursor=G;return}d.plan.push(G),v.push(J)}},jr=()=>{if(!j()||d.checking)return!1;let E=me();if(E===null||!j())return!1;let k=et();if(k===null||!j()||(Ie(E,k),!j()||d.checking||!v.length))return!1;if(d.frozenStart!==null&&EE)return!0;let z=v[0],Z=d.plan.findIndex(_=>_.key===z.key);if(Z<0)return Q("cancelled","context-changed"),!1;if(z.context.frag.start+z.context.frag.duration<=E+(k+(d.planningServiceMs??0))/1e3){if(!d.hopAvailable)return!1;d.hopAvailable=!1,d.cursor=d.plan[Z],d.plan.splice(Z,1),v.shift(),Ie(E,k);let _=v[0]?.context.frag.start;return _>E&&(d.frozenStart=_),!1}return!0},ft=()=>{if(d.poll!==null||!j())return;let E=d.deadline-performance.now();if(E<=0)return Q("failed","deadline");d.poll=setTimeout(()=>{if(d.poll=null,!!j()){if(!d.checking){d.hopAvailable=!0;let k=me();if(k===null||!j())return;if(!l())return Q("cancelled","not-allowed");let z=et();if(z===null||!j()||(Ie(k,z),!j()))return;W(k),queueMicrotask(q)}ft()}},Math.min(el,E))},St=(E,k=null)=>{let z=d.verified&&d.response?[{...d.own,permit:d.permit}]:[],Z=(k??[...z,...S.values()]).filter(X=>X.scope===y&&dt(X)).sort((X,G)=>X.context.frag.start-G.context.frag.start),_=null,K=null,J=[];for(let X of Z){let G=X.context.frag.start,te=G+X.context.frag.duration;_===null?G<=E&&EK&&(K=te,J.push(X))}return d.verifiedStart=_,d.verifiedEnd=K,{start:_,end:K,rows:J}},nr=(E=void 0)=>{if(!j())return null;if(E===void 0&&(E=me()),E===null||!j())return;if(!l())return Q("cancelled","not-allowed");let k;try{k=p(d.own.context)}catch{}if(!Number.isFinite(k)||k<0)return Q("failed","invalid-recovery");d.requiredHeadroomMs=k;let z=St(E);if(!(z.end===null||(z.end-E)*1e3new Promise((k,z)=>{let Z=!1,_=J=>{Z||(Z=!0,E.removeEventListener("abort",K),J?k():z(null))},K=()=>_(!1);if(E.addEventListener("abort",K,{once:!0}),E.aborted)return K();try{Promise.resolve(u(Object.freeze({signal:E}))).then(()=>_(!0),()=>_(!1))}catch{_(!1)}}),W=async(E=void 0)=>{if(!j()||d.checking||!d.verified)return;let k=nr(E);if(!k)return;d.checking=!0;let z=d.owner,Z=d.terminal,_=f,K=new Map,J=[],X=!0,G=()=>{if(X){X=!1;for(let ue of J){let he=(O.get(ue)??0)-1;he>0?O.set(ue,he):O.delete(ue)}d.releasePins===G&&(d.releasePins=null)}};d.releasePins=G;let te=()=>[...K.values()].some(({key:ue,row:he,identity:de})=>S.get(ue)!==he||!ut(Ae(he.context),de)||he.data.byteLength!==he.permit.size)?(Q("failed","coverage-evicted"),!1):[...K.values()].some(({key:ue,row:he})=>!pe({key:ue,scope:he.scope,context:he.context}))?(Q("cancelled","context-changed"),!1):!0,xe=async({covered:ue})=>{for(let[ye,le]of S)ue.rows.includes(le)&&!K.has(le)&&(K.set(le,{key:ye,row:le,identity:Ae(le.context)}),J.push(le.permit.key),O.set(le.permit.key,(O.get(le.permit.key)??0)+1));let he=[{context:d.own.context,permit:d.permit},...ue.rows.filter(ye=>ye.context!==d.own.context)],de=await Promise.all(he.map(ye=>t(ye.context,d.controller.signal)));return()=>{if(!j()||f!==_)return;if(de.some((ce,Pe)=>!ce||ce.key!==he[Pe].permit.key||ce.size!==he[Pe].permit.size||ce.sha256!==he[Pe].permit.sha256))return Q("failed","authority-changed");let ye=me();if(ye===null||!j())return;if(!l())return Q("cancelled","not-allowed");let le;try{le=p(d.own.context)}catch{}if(!Number.isFinite(le)||le<0)return Q("failed","invalid-recovery");if(d.requiredHeadroomMs=le,de.some((ce,Pe)=>typeof ce.current!="function"||ce.current(he[Pe].context)!==!0))return Q("failed","authority-changed");if(!j())return;if(performance.now()>=d.deadline)return Q("failed","deadline");if(!te())return;let be=St(ye,ue.rows);if(!(be.end===null||(be.end-ye)*1e3=d.deadline)return Q("failed","deadline");if(d.commitCompleted=!0,!te())return;let le=nr();if(!le||(ue=await xe(le),!ue()))return}let he=d.response,de=Z.context[Te];if(o?.(Z.context,he[0].data.byteLength,de?.peerBytes??0),!j())return;if(!l())return Q("cancelled","not-allowed");if((de?.commit??de?.accept)?.(Z.context),!j())return;de?.peerBytes>0&&(w.consumedPeerBytes+=de.peerBytes),d.state="ready",d.reason=null,d.released++,d.planningServiceMs=null,clearTimeout(d.timer),d.timer=null,clearTimeout(d.poll),d.poll=null,d.reserved=0;let ye=d.controller;if(d.owner=null,d.terminal=null,d.response=null,d.plan=[],d.cursor=null,d.frozenStart=null,!c){v=[];for(let le of[...U.values()])H(le)}try{z.deliver(Z,"onSuccess",he)}finally{try{ye.abort()}finally{de?.notify?.()}}}catch{j()&&Q("failed","authority-refused")}finally{G(),d.checking=!1,d.state==="buffering"&&(queueMicrotask(q),d.recheck&&(d.recheck=!1,queueMicrotask(W)))}},ve=(E,k,z,Z)=>{if(!d.enabled)return!0;if(d.state==="failed"||d.state==="cancelled")return d.state==="cancelled"&&(E.stats.aborted=!0),E.deliver(k,d.state==="cancelled"?"onAbort":"onError",d.state==="cancelled"?[E.stats,k.context,null]:[V(d.reason),k.context,null,E.stats]),!1;if(!z)return d.state==="idle"&&k.context.frag?.type==="main"&&k.context.frag.sn!=="initSegment"?(d.state="failed",d.reason="unsupported-context",d.failures++,E.deliver(k,"onError",[V(d.reason),k.context,null,E.stats]),!1):!0;if(d.state==="buffering")return Q("cancelled","superseded"),E.deliver(k,"onAbort",[E.stats,k.context,null]),!1;if(d.state!=="idle")return!0;let _=performance.now(),K=Z?.loadPolicy?.maxLoadTimeMs??Z?.timeout;if(Object.assign(d,{state:"buffering",owner:E,terminal:k,own:z,revision:f,reserved:We,entryAt:_,identity:{key:z.key,scope:z.scope,context:{frag:{start:z.context.frag.start,duration:z.context.frag.duration}}},contextUrl:k.context.url,fragUrl:k.context.frag.url,controller:new AbortController,deadline:_+Math.min(rr,Number.isFinite(K)&&K>0?K:rr)}),d.plan=(B?.upcoming??[]).map(J=>ge(J,z)),B?.owner===k.id&&(B.rolling=d.plan),d.cursor=null,k.context[Te]={peerBytes:0,genuine:()=>j()?{at:_,context:k.context}:null},!dt(z)||!l())return Q("failed","not-allowed"),!1;if(E.config.progressive===!0)return Q("failed","progressive-unsupported"),!1;if(me()===null||!j())return!1;try{if(!s(A()))return Q("failed","reservation-refused"),!1}catch{return Q("failed","reservation-refused"),!1}return j()?l()?(d.timer=setTimeout(()=>Q("failed","deadline"),Math.max(0,d.deadline-performance.now())),ft(),Promise.resolve().then(()=>j()?t(z.context,d.controller.signal):null).then(J=>{if(j()){if(!J||!Number.isSafeInteger(J.size)||J.size<1||J.size>We)return Q("failed","first-authority-refused");if(d.permit=J,d.reserved=J.size,!s(A()))return Q("failed","reservation-refused");w.highWaterBytes=Math.max(w.highWaterBytes,w.cacheBytes+A()),ie(),queueMicrotask(q)}}).catch(()=>{j()&&Q("failed","first-authority-refused")}),!0):(Q("cancelled","not-allowed"),!1):!1},ie=async()=>{if(!(!j()||!d.response||!d.permit||d.verifying||d.verified)){d.verifying=!0;try{let E=d.response[0].data,k=d.permit;if(!(E instanceof ArrayBuffer)||E.byteLength!==k.size||!await r(k,E,d.own.context,d.controller.signal))return j()&&Q("failed","first-integrity");if(!j())return;d.verified=!0,w.verified++,w.verifiedBytes+=E.byteLength,w.verifiedPeerBytes+=d.terminal.context[Te]?.peerBytes??0,W()}catch{j()&&Q("failed","first-integrity")}finally{d.verifying=!1}}};return{Loader:class{static relayswarmShadow=!0;constructor(k){this.config=k,this.inner=new n(k),this.stats=this.inner.stats,this.context=null,this.token=0}load(k,z,Z){this.abort(),this.context=k;let _={id:++$,context:k,callbacks:{...Z},settled:!1};this.pendingTerminal=_,Z={...Z};for(let xe of["onSuccess","onError","onTimeout","onAbort"])Z[xe]=(...ue)=>this.complete(_,xe,ue);let K=++this.token,J=ee(k,this.config,z,_.id),X=J&&S.get(J.key);if(!ve(this,_,J,z))return;let G=!X&&J&&U.get(J.key),te=X??G?.promise;if(te){G&&(w.coalesced++,G.waiters.add(this),this.warmPending=G,G.noteDemand(),m===G&&C.size===0&&(m=null,C.add(G),G.promote(),w.promotions++)),this.reuseAbort=new AbortController;let xe=f,ue=null,he,de=null,ye=()=>K===this.token,le=()=>{if(clearTimeout(he),F.delete(be),de!==null){let ce=O.get(de)-1;ce>0?O.set(de,ce):O.delete(de),de=null}},be=(ce=!1)=>{if(ce&&(le(),this.reuseAbort.abort()),!ye()||ue||this.originStarted)return;this.originStarted=!0,clearTimeout(he);let Pe={...Z,onProgress:(...Ce)=>{!ye()||ue==="cache"||(Ce[2]?.byteLength>0&&(ue="origin",this.reuseAbort.abort(),le()),Z.onProgress?.(...Ce))}};for(let Ce of["onSuccess","onError","onTimeout","onAbort"])Pe[Ce]=(...Ht)=>{!ye()||ue==="cache"||(ue="origin",this.reuseAbort.abort(),le(),Z[Ce]?.(...Ht))};this.start(k,z,Pe,K)};this.cancelReuse=()=>{le(),this.reuseAbort.abort()},F.add(be),Promise.resolve(te).then(async ce=>{if(!ye())return;if(this.releasePending(),g||!ce||xe!==f)return be(!0);if(ce.failure){let{name:Gn,args:Wr,stats:Yn}=ce.failure;ue="origin",le(),this.reuseAbort.abort(),Yn&&Object.assign(this.stats,Yn),Gn==="onError"?Z.onError(Wr[0],k,Wr[2],this.stats):Z[Gn](this.stats,k,Wr[2]);return}de=ce.permit.key,O.set(de,(O.get(de)??0)+1);let Pe=Math.max(0,Math.min(25,a(k)||0));Pe>0?he=setTimeout(be,Pe):be();let Ce;try{Ce=await t(k,this.reuseAbort.signal)}catch{}if(!ye()||ue==="origin")return;if(g||xe!==f)return be(!0);if(!Ce||Ce.key!==ce.permit.key||Ce.size!==ce.permit.size||Ce.sha256!==ce.permit.sha256)return N(J.key),be();ue="cache",le(),this.originStarted&&this.inner.abort(),Object.assign(this.stats,ce.stats);let Ht=ce.data.slice(0);w.localReuseBytes+=Ht.byteLength,ce.accepted||(ce.accepted=!0,ce.accept?.(k),w.consumedPeerBytes+=ce.peerBytes),o?.(k,Ht.byteLength,ce.peerBytes),Z.onSuccess({...ce.response,data:Ht},this.stats,k,ce.details),queueMicrotask(q)})}else this.start(k,z,Z,K);queueMicrotask(q)}start(k,z,Z,_){L.add(this),L.size+C.size>1&&m&&H(m);let K=this.pendingTerminal,J=()=>{L.delete(this),queueMicrotask(q)},X={...Z};X.onProgress=(...G)=>{if(!(g||_!==this.token||!K||K.settled||this.pendingTerminal!==K)){if(d.owner===this&&(G[0]?.loaded>(d.permit?.size??We)||G[2]?.byteLength>(d.permit?.size??We)))return Q("failed","first-oversize");if(d.owner===this&&G[2]!==null&&G[2]!==void 0){j();return}Z.onProgress?.(...G)}};for(let G of["onSuccess","onError","onTimeout","onAbort"])X[G]=(...te)=>{J(),_===this.token&&Z[G]?.(...te)};this.inner.load(k,z,X)}releasePending(){let k=this.warmPending;this.warmPending=null,k&&(k.waiters.delete(this),k.waiters.size||k.context[Te]?.onGenuine?.(),C.has(k)&&!k.waiters.size&&H(k))}complete(k,z,Z){if(!(!k||k.settled||this.pendingTerminal!==k)){if(d.owner===this&&d.terminal===k&&d.state==="buffering"){if(z==="onSuccess"){let _=Z[0]?.data;if(!(_ instanceof ArrayBuffer)||_.byteLength>(d.permit?.size??We))return Q("failed","first-oversize");d.response=Z,ie();return}d.state=z==="onAbort"?"cancelled":"failed",d.reason=z==="onAbort"?"origin-abort":"origin-error",z==="onAbort"?d.cancellations++:d.failures++,clearTimeout(d.timer),clearTimeout(d.poll),d.poll=null,d.controller?.abort(),d.releasePins?.(),d.owner=null,d.terminal=null,d.response=null,d.reserved=0,v=[],d.plan=[],d.cursor=null,d.frozenStart=null,d.planningServiceMs=null;for(let _ of[...U.values()])H(_);for(let _ of S.keys())N(_)}this.deliver(k,z,Z)}}deliver(k,z,Z){!k||k.settled||this.pendingTerminal!==k||(z!=="onSuccess"&&B?.owner===k.id&&(B=null),k.settled=!0,this.pendingTerminal=null,k.callbacks[z]?.(...Z))}cancel(k){let z=this.pendingTerminal;d.owner===this&&d.terminal===z&&Q("cancelled","caller-abort",!k&&!g),z&&B?.owner===z.id&&(B=null),this.token++,this.originStarted=!1,this.cancelReuse?.(),this.releasePending(),L.delete(this),z&&(this.stats.aborted=!0),k&&z&&(z.settled=!0,this.pendingTerminal=null);try{k?this.inner.destroy():this.inner.abort()}finally{k||this.complete(z,"onAbort",[this.stats,z?.context,null])}}abort(){this.cancel(!1)}destroy(){this.cancel(!0)}getCacheAge(){return this.inner.getCacheAge?.()??null}getResponseHeader(k){return this.inner.getResponseHeader?.(k)??null}},clear:D,startupSnapshot:()=>({enabled:d.enabled,state:d.state,reason:d.reason,heldObjects:d.state==="buffering"?x():0,heldBytes:d.state==="buffering"?w.cacheBytes+A():0,targetTime:d.targetTime,verifiedStart:d.verifiedStart,verifiedEnd:d.verifiedEnd,requiredHeadroomMs:d.requiredHeadroomMs,planningServiceMs:d.planningServiceMs,released:d.released,failures:d.failures,cancellations:d.cancellations,commitStarted:d.commitStarted,commitCompleted:d.commitCompleted,limits:{objects:Fn,bytes:We,deadlineMs:rr}}),contains(E){if(g||!l()||!Number.isFinite(E))return!1;for(let z of[...U.values(),...S.values()])if(z.scope===y&&jn(z,E))return!0;let k=B;if(!k||k.own.scope!==y||!jn(k.own,E))return!1;try{let z=k.rolling??e(k.own.context).map(Ae).filter(Boolean).filter(_=>_.scope===y).slice(0,2),Z=new Map([k.own,...z].map(_=>[_.key,_]));return(k.rolling?z.some(_=>!ne(_)):z.length!==k.upcoming.length||z.some((_,K)=>!ut(_,k.upcoming[K])))||[...U,...S].some(([_,K])=>!ut({...K,key:_},Z.get(_)))?(B=null,!1):!0}catch{B=null}return!1},pinned:E=>O.has(E),release(E){for(let[k,z]of S)z.permit.key===E&&N(k)},stop(){g=!0,D()},snapshot:()=>({...w,reservationBytes:A(),active:+!!m,promoted:C.size,trackedObjects:x(),queued:v.length,cacheObjects:S.size,limits:{objects:R(),bytes:We,speculativeWholeRequests:1,deadlineMs:rr,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},h=!1,u=null,p=v=>{if(!v.waiting)return;let b=Math.max(0,n()-v.queuedAt);c.waited++,c.waitTotalMs+=b,c.waitMaxMs=Math.max(c.waitMaxMs,b)},g=(v,b)=>{a.get(v.link)===v&&(a.delete(v.link),p(v),c[b]++,i(b),v.resolve(null))},f=(v,b=!1)=>{l.delete(v)&&(v.active=!1,b||t(v.charge),queueMicrotask(m))},m=()=>{if(clearTimeout(u),u=null,!h)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 b=v.deadline-n();u=setTimeout(m,Math.max(1,Math.ceil(Math.min(b,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)}},y=v=>{for(let b of[...a.values()])(!v||b.link===v)&&g(b,"cancelled");for(let b of[...l])(!v||b.link===v)&&(c.cancelled++,b.controller.abort(),f(b));m()};return{acquire(v,b){return h||a.has(v)||[...l].some(T=>T.link===v)||a.size>=o||!b.range&&(a.size||r(b.charge)>0)?(c.refused++,i("refused"),Promise.resolve(null)):new Promise(T=>{let B=n();a.set(v,{link:v,key:b.key,size:b.size,charge:b.charge,range:b.range?{start:b.range.start,end:b.range.end}:null,queuedAt:B,deadline:B+250,resolve:T,waiting:a.size>0,active:!1}),m()})},finish:f,cancel:y,recheck:m,stop(){h=!0,y(),clearTimeout(u),u=null},snapshot:()=>({enabled:!0,...c,queued:a.size,reservedBytes:[...l].reduce((v,b)=>v+b.charge,0),limits:{waitMs:250,waiters:o,perLink:1}})}}var nl=2,zr="webrtc",Wi=16,Wn=3e4,sl=1e4,Ki=300,Kn=32*1024,Vi=Object.freeze({mode:"shadow",originFallbackMs:1500,maxPeerWaitMs:5e3,originReserveMs:2e3,sustainablePeerWait:!1,warmAhead:!1,startupBufferTarget:null,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}),il=32768,ol=500,al=2e3,I=()=>performance.now(),qr=n=>{let e=n?.loading?.first;return Date.now()-(Number.isFinite(e)&&e>0&&e<=I()?I()-e:0)},eo=n=>Array.from(new Uint8Array(n),e=>e.toString(16).padStart(2,"0")).join(""),$i=new TextEncoder;async function Nt(n){return eo(await globalThis.crypto.subtle.digest("SHA-256",n))}function Gi(n){return new URL(n,globalThis.location?.href).pathname}function ll(n){try{return new URL(n,globalThis.location?.href).origin}catch{return String(n)}}function _e(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 cl(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 Vn(n){return{p50:_e(n,.5),p90:_e(n,.9)}}function Ke(n,e){n.push(e),n.length>ol&&n.shift()}function Pt(){let n=globalThis.navigator?.connection;return!!(n&&(n.type==="cellular"||n.saveData))}var Fr=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"]}),Ve=n=>Math.min(Number.MAX_SAFE_INTEGER,n+1),Yi=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"]),Zi=Object.freeze(["payload","none","timeout","abort","abandoned","closed","busy","send-error"]),hl=15e3,ul=250,dl=50,Xi=Object.freeze(["presence","dialStart","offerBeforeSend","offerIncoming","answerIncoming","glareBeforeRollback","glareAfterRollback","answerBeforeSend","upload","refresh","other"]),fl=Object.freeze(["admission","not-held","not-serving","banned","session-allowance","peer-limit","rate-limit","reservation-refused","reservation-inactive"]);function Ji(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 pl(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 gl(){return eo(globalThis.crypto.getRandomValues(new Uint8Array(12)))}function Qi(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 bl(n={}){let e=new $n(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 $n=class{constructor(e){this.options={...Vi,...e},this.options.iceTransportPolicy===void 0&&(this.options.iceTransportPolicy=Vi.iceTransportPolicy),this.startedAt=Date.now(),this.transportStartedAt=I(),this.transportSequence=0,this.transportRecords=[],this.transportDropped=0,this.transportCounters=Object.fromEntries(Object.entries(Fr).map(([t,r])=>[t,Object.fromEntries(r.map(s=>[s,0]))])),this.transportConnections=new WeakMap,this.peerEligibilityRecords=[],this.peerEligibilityDropped=0,this.peerEligibilityCounters=Object.fromEntries(Yi.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(Zi.map(t=>[t,0])),this.uploadRefusalCounters=Object.fromEntries(fl.map(t=>[t,0])),this.admissionCallCounters=Object.fromEntries(Xi.map(t=>[t,0])),this.disabledReason=this.#n(),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 Lt,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={}}#n(){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"&&!Nr(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>il)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(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&&!we(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.#Je(t),this.options.warmAhead||this.options.startupBufferTarget){this.warmAhead=Fi({Loader:e.config.fLoader,steady:this.options.warmAhead,startupTarget:this.options.startupBufferTarget,startupCommit:this.options.startupBufferCommit,startupRecovery:i=>Math.max(this.options.originReserveMs,(_e(this.#W(i),.9)||0)*1.25+100),allowed:()=>this.#p()&&e.media?.paused!==!0&&!Pt(),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 at(u=>this.options.getCommitment(i,{signal:u}),o,1e3);if(o.aborted||this.stopped)return null;let c=u=>!this.stopped&&this.#ce(l,{streamEvent:this.options.streamEvent,swarmId:this.options.swarmId,key:a,context:u,maxSegmentBytes:this.options.maxSegmentBytes,delegation:this.options.delegation,revokedDelegationIds:this.options.revokedDelegationIds,delegationRevocations:this.options.delegationRevocations}),h=c(i);return h&&h.size<=this.options.maxHeldBytes?{...h,key:a,current:u=>{let p=c(u);return!!(p&&p.size===h.size&&p.sha256===h.sha256)}}:null},verify:async(i,o,a,l)=>o instanceof ArrayBuffer&&o.byteLength===i.size&&!l.aborted&&await Nt(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,(_e(this.#W(i),.9)||0)*1.25+100);for(let c=0;ca)return Math.min(25,Math.max(0,(h-a)*1e3-l))}}catch{}return 0},onVerified:(i,o)=>(this.#rt(i.key),this.#T(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(al,r);this.coreRelease=r,this.coreWait=s.then(()=>{clearTimeout(i),this.timers.delete(i),this.coreWait=null,this.coreRelease=null}),this.#r("core",()=>this.#it().finally(r))}this.#r("start",()=>this.#lt()),typeof this.options.onMetrics=="function"&&this.#k(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,h]of l)h?Object.defineProperty(o,c,h):delete o[c]}},e.trigger=this.withheldTrigger)}updateTicket(e){return this.stopped||this.disabledReason||!this.#G()||!we(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.#F(),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.#se(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=Ve(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,h=g=>{let f=g;try{f??=r()}catch{}let m=y=>{try{let v=f?.[y];return Number.isSafeInteger(v)&&v>=0?v:null}catch{return null}};return{loaderLoadedBytes:m("loaded"),loaderTotalBytes:m("total")}},u=(g,f)=>this.#e({k:g,load:e,leg:t,at:this.#s(),ms:Math.round(I()-s),ranged:!1,...f});return u("originStart",{}),{progress:(g,f,m)=>{if(m){c||(c=!0,u("originCallback",{phase:"progress",outcome:null,stale:!0}));return}a||f!==!0||(a=!0,u("originProgress",{stale:!1,...h(g)}))},abortRequest:g=>{o||l||(l=!0,u("originAbortRequest",{reason:g,...h()}))},terminal:(g,f=null,m,y=!1)=>p(g,f,m,y)};function p(g,f,m,y){if(o){c||(c=!0,u("originCallback",{phase:"terminal",outcome:g,stale:!0}));return}o=!0;let v=y?{loaderLoadedBytes:null,loaderTotalBytes:null}:h(m);u("origin",{at:Math.floor(s)-i,outcome:g,bytes:Number.isSafeInteger(f)&&f>=0?f:null,stale:y,...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:nl,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:_e(this.signallingSamples,.5),p90Ms:_e(this.signallingSamples,.9),clock:{...this.session?this.session.clockDiagnostics():{aheadRejected:null,staleRejected:null,maxAheadSeconds:null,signalSamples:null,signalAgeMedianSeconds:null},origin:Xn(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:_e(this.peerLatencySamples,.5),peerLatencyP90Ms:_e(this.peerLatencySamples,.9),originLatencyMedianMs:_e(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.#L(),...this.multiHolder,originRangeOutcomes:{...this.originRangeOutcomes},timings:{durationMs:Vn(this.multiHolderTimings.map(o=>o[0])),slowestRequestMs:Vn(this.multiHolderTimings.map(o=>o[1])),requests:Vn(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)}#r(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.#r("timer",t)},Math.max(0,e));return this.timers.add(r),r}#k(e,t,r){let s=()=>{let i=e*t*(Math.random()*2-1);this.#h(e+i,()=>{try{r()}finally{s()}})};s()}#M(e,t){try{let r=Zn(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.#ze(s,a);if(t.#Y(s),t.options.peerSupplyHint&&t.#r("player-hint",()=>t.#B(s,l)),t.stopped||!s.frag||s.frag.sn==="initSegment"||s.part&&!t.options.swarmParts||!t.options.serveOnCellular&&Pt())return this.inner.load(s,i,o);if(l===0&&t.options.zeroBudgetPeerRace&&!this.hlsConfig.progressive&&t.#L()&&t.#l()){let S=new Map([...t.links.values()].filter(L=>t.#K(L,s)&&L.supportsRanges&&(t.remoteFraming.get(L.pubkey)??1)>=2&&!t.banned.has(L.pubkey)&&(L.have.size||t.options.lateHaveRace)).map(L=>[L,new Set(L.have)]));if(S.size)return this.loadCachedRace(s,i,o,a,S)}let c=i?.loadPolicy?.maxLoadTimeMs??i?.timeout;if(l===0&&t.options.latePeerRace&&!this.hlsConfig.progressive&&Ae(s)&&Number.isFinite(c)&&c>0&&t.#l())return this.loadLatePeerRace(s,i,o,a,c);let h=new AbortController,u={};this.active=u;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",y)};this.cancel=()=>{let S=this.active===u;return this.active=null,m(),h.abort(),S};let y=()=>{if(this.active!==u)return;this.active=null,this.pendingCallbacks=null,m(),h.abort(),t.counters.originFallbacks+=1,this.inner.stats.loading.start=0;let S=I(),L=!1,U=null,C=t.#C(s);C.then(w=>{!L&&!t.stopped&&(U=w,this.releaseFetch=t.#Z(w))}).catch(()=>{});let F=()=>L?!1:(L=!0,this.releaseFetch?.(),this.releaseFetch=null,!0),O=this.cancel;this.cancel=()=>(F(),O());let d=this.originTrace=t.#c(f,"fallback",()=>this.inner.stats);this.inner.load(s,i,{...o,onError:(...w)=>{d?.terminal("error",null,void 0,d!==this.originTrace),F(),o.onError?.(...w)},onTimeout:(...w)=>{d?.terminal("timeout",null,w[0],d!==this.originTrace),F(),o.onTimeout?.(...w)},onAbort:(...w)=>{d?.terminal("abort",null,w[0],d!==this.originTrace),F(),o.onAbort?.(...w)},onSuccess:(w,A,x,R)=>{if(L)return;let P=qr(A),{copy:N,size:M}=t.#S(w,s);if(!L&&(U&&N&&t.#T(U,new Uint8Array(N)),!!F())){if(this.pendingCallbacks=null,d?.terminal("payload",M||null,A,d!==this.originTrace),Ke(t.originLatencySamples,I()-S),t.#X(t.renditionOriginSamples,s,I()-S),t.options.peerSupplyHint&&M){let H=t.#v(s);!t.hintSizes.has(H)&&t.hintSizes.size>=16&&t.hintSizes.delete(t.hintSizes.keys().next().value),t.hintSizes.set(H,M);let D=I()-S;D>0&&Ke(t.hintOriginRates,M/D)}o.onSuccess(w,A,x,R),t.#M(R,P),M&&!t.stopped&&t.#r("peer-first-origin",async()=>{if(t.counters.originLoaded+=1,t.counters.bytesFromOrigin+=M,!U){let H=await C;N&&!t.stopped&&t.#T(H,new Uint8Array(N))}})}}})};if(l===0)return f=t.#i(s,0,0,a),t.#E(s,l,"no-budget",null,a),y();let v=()=>{$.onDeadline?.()||($.expired=!0,y())};g=setTimeout(v,l),t.lifecycle.signal.addEventListener("abort",y,{once:!0});let b=Math.max(t.options.originFallbackMs,t.options.maxPeerWaitMs),T=Math.max(l,Math.min(b,a.uncappedMs??l,a.sustainableMs??1/0));f=t.#i(s,l,T,a);let B={Loader:e,config:this.hlsConfig,loaderConfig:i},$={deadline:p+l,limit:p+T,originReserveMs:a.originReserveMs??t.options.originReserveMs,expired:!1,onDeadline:null,origin:B,extend:S=>{let L=Math.min($.limit,S);return this.active!==u||L<=$.deadline?!1:($.deadline=L,clearTimeout(g),g=setTimeout(v,Math.max(0,L-I())),!0)}};t.#ae(s,h.signal,$,l,a).then(S=>{if(!(this.active!==u||h.signal.aborted||t.stopped)){if(S&&!S.multi&&I()>=$.deadline&&t.#N(S.demand),!S||I()>=$.deadline&&!S.multi)return y();this.active=null,this.pendingCallbacks=null,m(),t.#O(this,S,s,o,p)}}).catch(S=>{this.active===u&&(t.#o("peer-first",S),y())})}loadCachedRace(s,i,o,a,l){let c=t.#i(s,0,t.options.maxPeerWaitMs,a),h={},u=new AbortController,p=I(),g=!0,f=!1,m=null,y,v;this.active=h,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 b=()=>{clearTimeout(v),t.lifecycle.signal.removeEventListener("abort",b),t.cachedRaces.delete(u),u.abort()};t.cachedRaces.add(u),t.lifecycle.signal.addEventListener("abort",b,{once:!0}),this.cancel=()=>{let S=g&&this.active===h;g=!1,this.active=null,b();try{this.inner.abort()}catch{}return S};let T=()=>!g||this.active!==h?!1:(g=!1,this.active=null,this.pendingCallbacks=null,b(),this.releaseFetch?.(),this.releaseFetch=null,!0);v=setTimeout(b,t.options.maxPeerWaitMs),t.counters.originFallbacks+=1,t.#E(s,0,"no-budget",null,a);let B=this.originTrace=t.#c(c,"cached",()=>this.inner.stats);try{this.inner.load(s,i,{...o,onProgress:(...S)=>{if(!g||this.active!==h){B?.progress(void 0,null,!0);return}let L=S[2]?.byteLength>0;L&&(f=!0,b()),B?.progress(S[0],L,!1),o.onProgress?.(...S)},onError:(...S)=>{B?.terminal("error",null,void 0,!g||this.active!==h),T()&&o.onError?.(...S)},onTimeout:(...S)=>{B?.terminal("timeout",null,S[0],!g||this.active!==h),T()&&o.onTimeout?.(...S)},onAbort:(...S)=>{B?.terminal("abort",null,S[0],!g||this.active!==h),T()&&o.onAbort?.(...S)},onSuccess:(S,L,U,C)=>{if((!g||this.active!==h)&&B?.terminal("payload",null,void 0,!0),!g||this.active!==h)return;let F=qr(L),{copy:O,size:d}=t.#S(S,s);!g||this.active!==h||(m&&O&&t.#T(m,new Uint8Array(O)),T()&&(B?.terminal("payload",d||null,L),Ke(t.originLatencySamples,I()-p),t.#X(t.renditionOriginSamples,s,I()-p),o.onSuccess(S,L,U,C),t.#M(C,F),d&&!t.stopped&&t.#r("cached-race-origin",async()=>{if(t.counters.originLoaded+=1,t.counters.bytesFromOrigin+=d,!m){let w=await(y??t.#C(s));O&&!t.stopped&&t.#T(w,new Uint8Array(O))}})))}})}catch(S){throw T(),S}if(!g)return;y=t.#C(s),y.then(S=>{g&&!t.stopped&&(m=S,this.releaseFetch=t.#Z(S))}).catch(()=>{});let $={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,u.signal,$,0,a).then(S=>{if(!(!S||!g||f||this.active!==h||u.signal.aborted||t.stopped||I()>=$.limit)){g=!1,this.active=null,this.pendingCallbacks=null,b(),this.releaseFetch?.(),this.releaseFetch=null,B?.abortRequest("peer-won");try{this.inner.abort()}catch{}t.counters.zeroBudgetPeerRaceWins+=1,t.#O(this,S,s,o,p)}}).catch(S=>{g&&!u.signal.aborted&&!t.stopped&&t.#o("cached-race",S)}).finally(b)}loadLatePeerRace(s,i,o,a,l){let c=t.#i(s,0,l,a),h={},u=new AbortController,p=I(),g=!0,f=!1,m=null,y;this.active=h,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===h&&!t.stopped,b=B=>!g||this.active!==h?!1:(g=!1,this.active=null,this.pendingCallbacks=null,y?.close(B),this.releaseFetch?.(),this.releaseFetch=null,!0);this.cancel=()=>{let B=g&&this.active===h;g=!1,this.active=null,y?.close("caller-abort"),this.releaseFetch?.(),this.releaseFetch=null;try{this.inner.abort()}catch{}return B};let T;y=t.#w({context:s,controller:u,entryAt:p,parentDeadline:p+l,current:v,arm:(B,$)=>(t.options.traceRequests&&t.traceLoads.set(B,c),t.#ae(B,u.signal,$,0,a).then(S=>{if(!S||!v()||u.signal.aborted||I()>=$.limit||!y.valid()||typeof $.revalidateAuthority!="function"||!$.revalidateAuthority())return!1;g=!1,this.active=null,this.pendingCallbacks=null,y.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,S,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:(...B)=>{if(!g||this.active!==h){T?.progress(void 0,null,!0);return}let $=B[2]?.byteLength>0;$&&(f=!0,y?.close("origin-progress")),T?.progress(B[0],$,!1),o.onProgress?.(...B)},onError:(...B)=>{T?.terminal("error",null,void 0,!g||this.active!==h),b("origin-error")&&o.onError?.(...B)},onTimeout:(...B)=>{T?.terminal("timeout",null,B[0],!g||this.active!==h),b("origin-timeout")&&o.onTimeout?.(...B)},onAbort:(...B)=>{T?.terminal("abort",null,B[0],!g||this.active!==h),b("origin-abort")&&o.onAbort?.(...B)},onSuccess:(B,$,S,L)=>{if((!g||this.active!==h)&&T?.terminal("payload",null,void 0,!0),!g||this.active!==h)return;let U=qr($),{copy:C,size:F}=t.#S(B,s);!g||this.active!==h||(m&&C&&t.#T(m,new Uint8Array(C)),b("origin-success")&&(T?.terminal("payload",F||null,$),Ke(t.originLatencySamples,I()-p),t.#X(t.renditionOriginSamples,s,I()-p),o.onSuccess(B,$,S,L),t.#M(L,U),F&&!t.stopped&&t.#r("late-race-origin",async()=>{if(t.counters.originLoaded++,t.counters.bytesFromOrigin+=F,!m){let O=await(y?.keyPromise??t.#C(s));C&&!t.stopped&&t.#T(O,new Uint8Array(C))}})))}})}catch(B){throw b("origin-throw"),B}g&&y?.keyPromise.then(B=>{g&&this.active===h&&!t.stopped&&(m=B,this.releaseFetch=t.#Z(B))}).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?.[Te]?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)}#A(){for(let e of[...this.latePeerOwners.values()])e.refresh()}#w(e){let t=Ae(e.context);if(!t||!this.#l())return null;let r=e.context[Te],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},h=(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),u=()=>{let p=c();return!p||!Number.isFinite(p.at)||Ae(p.context)?.key!==t.key?null:r?{...p.context,[Te]:r}:p.context};o.valid=()=>!o.closed&&e.current()&&!this.stopped&&o.generation===this.latePeerGeneration&&o.streamId===this.options.streamEvent?.id&&u()!==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=u();if(!g||i?.paused||i?.ended)return o.close("context-or-playback");if(o.windowEnd===null){let y=p.role==="startup-buffer-dependency";o.genuineAt=y?null:p.at,o.dependencyAt=y?s:null,o.dependencyDeadline=y?p.deadline:null,o.windowEnd=Math.min(e.parentDeadline,y?p.deadline:1/0,(y?s:p.at)+Math.min(4e3,this.options.lateWindowMs)),y&&p.signal.addEventListener("abort",()=>o.close("startup-buffer-ended"),{once:!0,signal:a.signal}),this.#f(o,"entered",y?"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.#L())return;let f=[...this.links.values()].filter(y=>h(y,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 y=await Promise.all(f.map(async S=>{if(!this.options.admit)return S;let L=this.admissionChecks.get(S.pubkey)?.ticket??this.admitted.get(S.pubkey)?.ticket,U=!1;try{U=await at(()=>this.#x(S.pubkey,L,"other"),o.controller.signal,Math.max(0,Math.min(this.options.admissionTimeoutMs,m-I())))===!0}catch{}return!U&&!o.closed&&S.close("admission"),U?S:null}));if(o.closed)return;let v=u();if(!e.current()||!v||I()>=m||o.generation!==this.latePeerGeneration)return o.close("inactive-after-admission");let b=y.filter(S=>S&&h(S,v));if(!b.length)return o.close("admission-or-have-refused","refused");o.validatedPeers=new Map(b.map(S=>[S,this.admitted.get(S.pubkey)?.ticket]));let T=Ae(v)?.context;if(!T||!o.valid())return o.close("context-after-admission");let B={deadline:m,limit:m,originReserveMs:0,expired:!1,onDeadline:null,knownKey:o.key,cachedOnly:new Map(b.map(S=>[S,new Set([o.key])])),lateHaveRace:!1,peerOnly:!0,extend:()=>!1,currentValid:o.valid,revalidateAuthority:!0};!await e.arm(T,B)&&!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.#F(),this.firstPeerSegmentAtMs===null&&(this.firstPeerSegmentAtMs=Date.now()-this.startedAt),Ke(this.peerLatencySamples,o-i),p.frag&&this.peerFragments.add(p.frag)}},h=()=>{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{}}},u=p=>{c(p),h()};r[Te]?Object.assign(r[Te],{peerBytes:l,accept:u,commit:c,notify:h}):u(r),!r[Te]&&this.#p()&&!this.held.has(t.key)&&this.#T(t.key,t.bytes.slice()),s.onSuccess({url:r.url,data:t.bytes.buffer,code:200},e.peerStats,r,null)}async#B(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(h=>h.sn===e.frag.sn&&h.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}`,h=a?await this.#C(a):null;if(this.stopped||r!==this.hintGeneration)return null;let u=a&&this.discovery.contexts.get(a.frag.type||"main"),p=h?[...this.links.values()].filter(T=>this.#P(T)&&T.have.has(h)&&T.supportsRanges===!0&&(this.remoteFraming.get(T.pubkey)??1)>=2&&!this.banned.has(T.pubkey)&&!(u?.rendition===c&&this.discovery.stale(u,T.pubkey))).map((T,B)=>{let $=this.peerSelection.summary(T).throughputBytesPerSecond;return[B+1,null,$?$/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),y=_e(this.renditionOriginSamples.get(c)||[],.5),v={rendition:c,size:m,peers:p,origin:[null,m&&y?m/y:_e(this.hintOriginRates,.5)],sharedFirstByteMs:this.peerSelection.firstByteMs(),sharedRate:this.peerSelection.rate(),availableMs:t,maxHolders:this.options.maxHoldersPerObject},b=this.core?.playerHint(v);return b&&this.options.traceRequests&&this.#e({k:"playerHint",at:this.#s(),input:v,out:b}),b?{...b,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=_t(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=Ae(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,h)=>(parseInt(c,16)^parseInt(e[h],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)}}}#ze(e,t){if(e?.[Te])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=_e(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,(_e(this.#W(e),.9)||0)*1.25+100),a,l,c,h=(a=e?.part?.start)??e?.frag?.start,u=Number.isFinite(h)&&h>r.currentTime?Math.min(l=r.buffered.end(i),h):l=r.buffered.end(i),p=Math.max(0,(u-(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(u),fragmentStart:f(h),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||Gi)(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 Nt($i.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}#Fe({key:e,rendition:t,context:r}){let s=l=>l.sort((c,h)=>c-h).slice(0,8),i=[],o=[],a=[];for(let l of this.links.values()){let c=this.#U(l.pubkey);this.#q(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(h=>this.#q(h,i));if(t&&![...this.links.values()].some(h=>h.have.has(s))){for(let h of a)this.discovery.holderMiss(o,h.pubkey,s);return}let l=a.filter(h=>e.asked.has(h.pubkey)||r.includes(h.pubkey)),c=[];for(let h of l)this.discovery.holderMiss(o,h.pubkey,s)&&(this.discovery.counters.heldMiss++,c.push(this.#U(h.pubkey)));c.length&&e.row?.heldMissHolders&&(e.row.heldMissHolders=c.sort((h,u)=>h-u).slice(0,8))}catch{}}}#je(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(!Yi.includes(r))return;let h=m=>Number.isSafeInteger(m)&&m>=0?m:null,u=null,p=null;try{u=h(e?.frag?.cc)}catch{}try{p=h(e?.frag?.level)}catch{}let g=I()-this.transportStartedAt,f={atMs:Number.isFinite(g)?Math.max(0,Math.round(g)):0,cc:u,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.#Fe(a))}catch{Object.assign(f,{holders:null,haveHolders:null,staleHolders:null,heldMissHolders:null})}a.row=f}this.peerEligibilityCounters[r]=Ve(this.peerEligibilityCounters[r]),this.peerEligibilityRecords.length===64&&(this.peerEligibilityRecords.shift(),this.peerEligibilityDropped=Ve(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)||[];Ke(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}}#We(e,t,r,s){if(!(t>0)||!Number.isFinite(t)||rWi&&o.firstBytes.shift();let l=s-r;l>=Ki&&i>=Kn&&(o.flows.push({value:Math.min(1e6,i/l),flowMs:l,at:a}),o.flows.length>Wi&&o.flows.shift())}#pe(e,t,r=null){if(!e||e.closed||!Number.isSafeInteger(t)||t<=0)return;let s=this.#oe(e);Number.isFinite(r)&&(s.flows=s.flows.filter(i=>i.at>=r)),s.usefulAt=I()}#Ve(e,t,r){let s=this.#oe(e),i=I();s.firstBytes=s.firstBytes.filter(u=>i-u.at<=Wn),s.flows=s.flows.filter(u=>i-u.at<=Wn);let o=s.firstBytes.reduce((u,p)=>u===null?p.value:(u+p.value)/2,null),a=s.flows.filter(u=>u.flowMs>=(o??0)*3),l=cl((a.length>=2?a:s.flows).map(u=>u.value),.75),c=l!==null&&(o??0)+r/l<=t,h=l===null&&(o??0)=sl)return{state:s,firstByteMs:null,rate:null,refresh:!0};if(l===null)return null}return{state:s,firstByteMs:o,rate:l,refresh:!1}}#$e(e,t){let r=_e(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>=hl?"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)}#J(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 O=w=>[...r.cachedOnly].filter(([A,x])=>(!w||x.has(c))&&A.have.has(c)&&this.links.get(A.pubkey)===A&&this.#K(A,e)&&!this.banned.has(A.pubkey)&&A.supportsRanges===!0&&(this.remoteFraming.get(A.pubkey)??1)>=2).map(([A])=>A),d=O(!0);if(!d.length&&r.lateHaveRace){for(d=O(!1);!d.length&&!t.aborted&&!this.stopped&&I()0}if(t.aborted||this.stopped||I()>=r.limit||(r.cachedHolders=new Set(d),!r.cachedHolders.size||!this.#L()))return null;this.counters.zeroBudgetPeerRaces+=1}let h=this.#v(e),u=l?.rendition===h&&this.discovery.contexts.get(l.mediaType)===l?l:null;if(u&&!r.cachedOnly){this.discovery.demand(l.mediaType,h,c);let O=this.discovery.counters.checks;this.#te();try{this.#je(u,O)}catch{}}let p={key:c,rendition:h,context:u,recorded:!1,asked:new Set,row:null},g=![...this.links.values()].some(O=>O.have.has(c));if(g&&!this.#I(c,h,e))return this.#E(e,s,"no-have-no-wait",!1,i,void 0,p,!1,o),null;let f=this.renditionSizes.get(h),m=g?this.#$e(c,h):0,y=f?this.peerSelection.projectMs(f):null,v=!g&&this.#L()&&[...this.links.values()].some(O=>this.#K(O,e)&&O.supportsRanges===!0&&O.have.has(c)&&!this.banned.has(O.pubkey)&&(this.remoteFraming.get(O.pubkey)??1)>=2&&!(u&&this.discovery.stale(u,O.pubkey))),b=r.cachedOnly||v?"unknown":this.#ge(y,m,r),T=null;if(b==="late"&&!g&&this.#be(p,r)&&(T=this.#J("entry",y,m,r),b="stretch"),b==="late")return this.#E(e,s,"projected-late",!g,i,this.#J("entry",y,m,r),p,!1,o),this.#N(p,{everyServing:!0}),this.counters.peerProjectedLate+=1,null;this.#me(b,m+y,r),g&&(this.#E(e,s,"no-have-wait",!1,i,void 0,p,!1,o),this.counters.coordinatedWaits+=1);let B=r.deadline-I();if(t.aborted||this.stopped||B<=0)return null;this.counters.commitmentRequests+=1;let $=at(O=>{if(t.aborted||this.stopped||I()>=r.deadline)throw new Error("Commitment load no longer active.");return this.options.getCommitment(e,{signal:O})},t,B).then(O=>({ok:!0,event:O}),()=>({ok:!1}));if(g){for(;!t.aborted&&!this.stopped&&I()d.have.has(c));){if(!this.#I(c,h,e))return this.#E(e,s,"wait-no-longer-eligible",!1,i,void 0,p,!1,o),null;await this.#Q(c,Math.min(100,r.deadline-I()),t)}let O=t.aborted||this.stopped;if(O||I()>=r.deadline)return this.#E(e,s,O?"wait-aborted":"wait-expired",null,i,void 0,p,!1,o),(!O||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 S,L;try{let O=await $;if(!O.ok)throw new Error("Commitment unavailable.");L=O.event,S=this.#ce(O.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(!S)return this.counters.commitmentRejected+=1,null;if(r.currentValid&&!r.currentValid()||(r.revalidateAuthority===!0&&(r.revalidateAuthority=()=>!!this.#ce(L,{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&&S.v!==3)return null;if(!this.renditionSizes.has(h)&&this.renditionSizes.size>=16&&this.renditionSizes.delete(this.renditionSizes.keys().next().value),this.renditionSizes.set(h,S.size),S.v===3&&this.options.multiHolder){let O=await this.#Ze(e,t,r,c,S,l,o);if(O!==void 0)return O&&g&&(this.counters.coordinatedPeerLoads+=1),O&&{...O,holderContext:u}}if(r.cachedOnly)return null;let U=this.peerSelection.projectMs(S.size),C=this.#ge(U,0,r);if(C==="late"&&!g&&(T!==null||this.#be(p,r))&&(T=this.#J("commitment",U,0,r),C="stretch",p.row&&(p.row.projection={...T},p.row.trial=!0)),C==="late")return this.#E(e,s,"projected-late",!0,i,this.#J("commitment",U,0,r),p,!1,o),this.counters.peerProjectedLate+=1,null;this.#me(C,U,r);let F=new Set;for(;!t.aborted&&!this.stopped&&I()O||(d??0)>O)return this.counters.peerSkippedLate+=1,null;let w=(V,re)=>this.peerSelection.estimate(V,S.size)===null||this.peerSelection.estimate(V,S.size)*1.25+25<=re,A=T&&F.size===0?this.#ye(c,p.context):null;A&&this.peerSelection.markSelected(A);let x=A??this.peerSelection.select([...this.links.values()].filter(V=>this.#P(V)),c,F,S.size,O);if(!x){if(![...this.links.values()].some(V=>!V.closed&&!F.has(V.pubkey)&&V.have.has(c)&&w(V,O)))return this.counters.peerNoFit+=1,this.#N(p,{unfit:[...this.links.values()].filter(V=>!V.closed&&!F.has(V.pubkey)&&V.have.has(c)&&!w(V,O)).map(V=>V.pubkey)}),null;await this.#Q(c,Math.min(100,r.deadline-I()),t);continue}F.add(x.pubkey),p.asked.add(x.pubkey),A&&(this.counters.peerUntestedTrial+=1);let R=this.peerSelection.estimate(x,S.size);R!==null&&r.extend(I()+R*1.25+25)&&(this.counters.peerWaitExtended+=1);let P=I(),N=r.deadline-I(),M=[...this.links.values()].filter(V=>this.#P(V)&&!F.has(V.pubkey)&&V.have.has(c)&&w(V,N)).length,H=N-Math.min(2,M)*25,D=R===null?Math.min(N,Math.max(25,H)):Math.min(N,Math.max(25,N/Math.min(3,M+1),R*1.25+25)),q=this.#Xe(t,P,S.size,r,d),ee;try{ee=await x.request(c,Math.max(1,D),{signal:q.signal,expectedSize:S.size,onProgress:q.progress,onResult:V=>this.#we(e,x,N,V,null,o)})}finally{q.done()}if(this.peerSelection.observe(q.observation()),q.abandoned)return this.#R(x,I()-P),this.counters.peerAbandoned+=1,this.#N(p),null;if(!ee||t.aborted||this.stopped){!t.aborted&&!this.stopped&&this.#R(x,I()-P);continue}let j=await Nt(ee);if(this.stopped)return null;if(ee.byteLength!==S.size||j!==S.sha256){if(this.#R(x,I()-P),this.counters.peerCorrupt+=1,this.banned.add(x.pubkey),p.asked.delete(x.pubkey),x.close("integrity"),t.aborted)return r.expired&&this.#N(p),null;continue}return t.aborted?(r.expired&&this.#N(p),null):S.expiresAt<=Math.floor(Date.now()/1e3)?null:(this.#R(x,I()-P,ee.byteLength),g&&(this.counters.coordinatedPeerLoads+=1),A&&(this.counters.peerUntestedTrialLoaded+=1),{key:c,bytes:ee,discoveryContext:l,holderContext:u,pubkey:x.pubkey,demand:p,connection:x.pc})}return!this.stopped&&(!t.aborted||r.expired)&&this.#N(p),null}#Ge(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?.[Te]&&!e.closed&&this.peerLeases.has(e))}#Ye(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#Ze(e,t,r,s,i,o,a){if(r.currentValid&&!r.currentValid())return null;let l=this.options.transferWorkerUrl!==void 0;if(l&&(!this.#L()||this.transferWorkerState!=="ready"))return null;if(!this.#L()||!Array.isArray(i.pieces))return;let c=ll(e.url);if(!r.peerOnly&&this.originsWithoutRanges.has(c))return l?null:void 0;let h=b=>this.links.get(b.pubkey)===b&&!b.closed&&b.supportsRanges===!0&&b.have.has(s)&&!this.banned.has(b.pubkey)&&(this.remoteFraming.get(b.pubkey)??1)>=2&&(!r.cachedHolders||r.cachedHolders.has(b)),u=[...this.links.values()].filter(b=>h(b)&&this.#K(b,e)),p=()=>u.filter(b=>h(b)&&this.#P(b)),g=p();if(!g.length&&e?.[Te]&&u.some(b=>this.peerLeases.has(b))&&(await this.#Ye(u,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(b=>[b,this.#Ve(b,Math.max(0,r.limit-I()),i.pieceSize)]).filter(([,b])=>b!==null));if(!f.size)return this.counters.peerNoFit+=1,null;let m=[...f.keys()],y={};for(let b of m)this.peerLeases.set(b,y);this.peerAdmission.claims+=m.length;let v=()=>{t.removeEventListener("abort",v);for(let b of m)this.peerLeases.get(b)===y&&this.peerLeases.delete(b);for(let b of[...this.peerLeaseWaiters])this.#h(0,b);this.latePeerOwners.size&&this.#h(0,()=>this.#A())};t.addEventListener("abort",v,{once:!0});try{let b=new Map(m.map(x=>[this.#Ge(x),x])),T=Math.floor(r.limit),B=r.peerOnly?r.limit:r.limit+r.originReserveMs,$={size:i.size,sha256:i.sha256,pieces:i.pieces,deadline:T,maxHolders:this.options.maxHoldersPerObject,originReserveMs:0,...r.peerOnly?{peerOnly:!0}:{}},S;try{S=l?await this.transferWorker.transfer($,{signal:t}):this.core.transfer($)}catch{return null}if(this.stopped||t.aborted||l&&I()>=T||r.currentValid&&!r.currentValid()||typeof r.revalidateAuthority=="function"&&!r.revalidateAuthority()||m.some(x=>!h(x)||x.busy||this.peerLeases.get(x)!==y))return S?.free(),null;if(!S)return l||r.peerOnly?null:void 0;this.multiHolder.transfers+=1;let L=a,U=this.traceBase,C=(x,R,P)=>{let N=Math.floor(I()),M=D=>(this.options.traceRequests&&this.#e({k:"xfer",load:L,op:x,at:N-U,...R,out:D&&{c:D.commands.map(({t:q,peer:ee,p:j})=>({t:q,...ee!==void 0?{peer:ee}:{},...j?{p:[...j]}:{}})),next:D.next===null?null:D.next-U,late:D.late,finished:D.finished}}),D),H=P(N);return H?.then?H.then(M):M(H)};r.extend(r.limit);let F=i.pieceSize,O=({start:x,end:R})=>[x*F,Math.min(R*F,i.size)],d=[...b].map(([x,R])=>[x,f.get(R).firstByteMs,f.get(R).rate]),w=r.peerOnly?null:_e(this.#W(e),.5),A=r.peerOnly?null:[0,w?i.size/w:null];return await new Promise(x=>{let R=new Map,P=new Set,N=new WeakSet,M=new Map,H=new Map,D=!1,q=null,ee=null,j=null,V=0,re=0,ae=(W,ve)=>{let ie=W?.verified==null?0:Math.max(0,W.verified-re);return W?.verified!=null&&(re=Math.max(re,W.verified)),this.multiHolder.unusedBytes+=ve-ie,ie},ge=I(),ne=0,pe=0,Q=W=>(W!==null&&(clearTimeout(W),this.timers.delete(W)),null),me=W=>{if(!D){D=!0,q=Q(q),ee=Q(ee);for(let ve of[...R.values(),...P])ve.abort();j?.(),r.onDeadline=null,t.removeEventListener("abort",et),S.free(),x(W)}},et=()=>me(null);t.addEventListener("abort",et,{once:!0});let Ie=(W,ve,ie,Be=ft)=>{if(D)return;let E=k=>{if(!D){if(r.currentValid&&!r.currentValid()||(l||r.peerOnly)&&I()>=B)return me(null);k?Be(k):me(null)}};try{let k=C(W,ve,ie);k?.then?k.then(E,()=>me(null)):E(k)}catch{me(null)}},jr=(W,ve)=>{if(W.t==="request"){let ie=b.get(W.peer),Be=new AbortController;R.set(W.peer,Be);let[E,k]=O(W.range),z=I(),Z=Math.max(1,T-z),_=null,K=-1/0;pe+=1,f.get(ie).refresh&&(f.get(ie).refreshStartedAt??=I(),f.get(ie).state.probeAt=I());let J=X=>{let G=I();D||R.get(W.peer)!==Be||G-KS.progress(te,W.peer,X)))};ie.request(s,Z,{signal:Be.signal,expectedSize:k-E,onProgress:J,range:{start:W.range.start,end:W.range.end,objectSize:i.size},onResult:X=>{_=X,this.#we(e,ie,Z,X,W.range,a)}}).then(X=>{R.get(W.peer)===Be&&R.delete(W.peer),ne=Math.max(ne,I()-z),!D&&(_?.firstByteMs!==null&&_?.elapsedMs!==null&&_?.receivedBytes&&this.peerSelection.observe({firstByteMs:_.firstByteMs,bytes:_.receivedBytes,flowMs:_.elapsedMs-_.firstByteMs}),X?(this.#R(ie,I()-z,X.byteLength),Ie("delivered",{source:W.peer,p:[W.range.start,W.range.end],bytes:X.byteLength},G=>S.delivered(G,W.peer,W.range,X),G=>{let te=ae(G,X.byteLength);this.multiHolder.peerBytes+=te,te>0&&M.set(ie.pc,(M.get(ie.pc)??0)+te);let xe=_?.elapsedMs-_?.firstByteMs;te>0&&f.get(ie).refresh&&_?.receivedBytes>=Kn&&Number.isFinite(xe)&&xe>=0&&xeS.failed(G,W.peer))))},()=>{D||Ie("failed",{source:W.peer},X=>S.failed(X,W.peer))})}else if(W.t==="origin"){if(r.peerOnly){this.multiHolder.failed+=1,me(null);return}j??=this.#Z(s);let ie=new AbortController,[Be,E]=O(W.range),k=I(),z=null,Z=K=>{z=K,this.originRangeOutcomes[K.outcome]=Ve(this.originRangeOutcomes[K.outcome])};P.add(ie),this.multiHolder.originRanges+=1;let _=()=>{this.originsWithoutRanges.has(c)||(this.originsWithoutRanges.add(c),this.multiHolder.originRangesIgnored+=1)};(r.origin?.Loader?Ui(r.origin,e,Be,E,{signal:ie.signal,onIgnored:_,onResult:Z}):zi(e,Be,E,{signal:ie.signal,onIgnored:_,onResult:Z})).then(K=>{if(P.delete(ie),this.options.traceRequests&&this.#e({k:"origin",load:L,at:this.#s(k),ms:Math.round(I()-k),ranged:!0,range:[W.range.start,W.range.end],outcome:z?.outcome??(K?"payload":D?"abort":"none"),httpStatus:z?.httpStatus??null,bytes:K?.byteLength??null}),D)return;let J=[W.range.start,W.range.end];if(!K)return Ie("failed",{source:"origin"},X=>S.failed(X,"origin"));this.#We(e,I()-k,K.byteLength,i.size),this.counters.bytesFromOrigin+=K.byteLength,Ie("delivered",{source:"origin",p:J,bytes:K.byteLength},X=>S.delivered(X,"origin",W.range,K),X=>{let G=ae(X,K.byteLength);this.multiHolder.originBytes+=G,V+=G,ft(X)})})}else if(W.t==="cancel"||W.t==="abandon"){let ie=R.get(W.peer);W.t==="abandon"&&(this.multiHolder.abandoned+=1,ie&&N.add(ie)),ie?.abort(W.t==="abandon"?ot.ABANDON_REASON:void 0)}else if(W.t==="ban"){let ie=b.get(W.peer);this.multiHolder.bans+=1,this.counters.peerCorrupt+=1,this.banned.add(ie.pubkey),ie.close("integrity")}else if(W.t==="deliver"){this.multiHolder.delivered+=1,this.multiHolderTimings.push([I()-ge,ne,pe]),this.multiHolderTimings.length>128&&this.multiHolderTimings.shift();let ie=ve.bytes.byteOffset===0&&ve.bytes.byteLength===ve.bytes.buffer.byteLength?ve.bytes:ve.bytes.slice();me(i.expiresAt<=Math.floor(Date.now()/1e3)?null:{key:s,bytes:ie,discoveryContext:o,multi:!0,peerBytes:Math.max(0,i.size-V),contributions:[...M].map(([Be,E])=>({connection:Be,bytes:E})),shortRefreshes:[...H].map(([Be,E])=>({connection:Be,at:E}))})}else W.t==="fail"&&(this.multiHolder.failed+=1,me(null))},ft=W=>{if(!D){if(!W)return me(null);for(let ve of W.commands)if(jr(ve,W),D)return;q=Q(q),W.next!==null&&(q=this.#h(Math.max(0,W.next-I()),()=>{q=null,Ie("tick",{},ve=>S.tick(ve))}))}};r.onDeadline=()=>D?!1:(Ie("tick",{},W=>S.tick(W)),!D&&ee===null&&(ee=this.#h(Math.max(0,r.limit+r.originReserveMs-I()),()=>{ee=null,me(null)})),!0);let St=[...f.values()].some(W=>W.refresh||W.firstByteMs===null)?null:this.peerSelection.firstByteMs(),nr=[...b].filter(([,W])=>f.get(W).rate===null).map(([W])=>W),sr={peers:d,origin:A,sharedFirstByteMs:St,sharedRate:this.peerSelection.rate(),probePeers:nr};Ie("start",this.options.traceRequests?{size:i.size,pieces:i.pieces.length,pieceSize:F,deadline:T-U,maxHolders:this.options.maxHoldersPerObject,originReserveMs:0,...r.peerOnly?{peerOnly:!0}:{},...structuredClone(sr),holders:[...b].map(([W,ve])=>[W,this.#U(ve.pubkey)])}:null,W=>S.start(W,sr),W=>{W?.late&&(this.multiHolder.late+=1),ft(W)})})}finally{v()}}#Xe(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(),h=null,u={abandoned:!1,signal:o.signal},p=()=>{u.abandoned||o.signal.aborted||(u.abandoned=!0,o.abort(ot.ABANDON_REASON))},g=null;if(i!==null){let m=c?s.deadline-r/c:-1/0;g=setTimeout(()=>{h===null&&p()},Math.max(ul,i*3,m-I()))}let f=m=>{let y=l.at(-1);if(!y)return null;let v=l[0];for(let b of l)if(b[0]<=y[0]-m)v=b;else break;return y[0]-v[0]>=150?{bytes:y[1]-v[1],ms:y[0]-v[0]}:null};return u.progress=(m,y,v)=>{let b=I();if(h===null&&(h=Number.isFinite(v)?v:b-t),l.push([b,m]),l.length>256&&l.shift(),b-ts.deadline)&&p()},u.observation=()=>{let m=l.length?l.at(-1)[0]-l[0][0]:0,y=f(Math.max(300,m/2));return{firstByteMs:h,bytes:y?.bytes??0,flowMs:y?.ms??0,totalFlowMs:m}},u.done=()=>{clearTimeout(g),e.removeEventListener("abort",a)},u}#R(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(!Zi.includes(s.outcome))return;this.#Ke(t,s);let a=p=>Number.isFinite(p)&&p>=0?p:null,l=p=>Number.isSafeInteger(p)&&p>=0?p:null,c=null,h=null;try{c=l(e?.frag?.cc)}catch{}try{h=l(e?.frag?.level)}catch{}let u={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:h,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:Fr["link-close"].includes(s.closeReason)?s.closeReason:null};this.peerRequestCounters[s.outcome]=Ve(this.peerRequestCounters[s.outcome]),this.peerRequestRecords.length===64&&(this.peerRequestRecords.shift(),this.peerRequestDropped=Ve(this.peerRequestDropped)),this.peerRequestRecords.push(u),this.#e({k:"request",load:o,at:this.#s(),range:i?[i.start,i.end]:null,...u})}catch{}}#Je(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.#Qe(i);if(this.race=l,!l)return this.inner.load(i,o,a);let c=[],h=0,u=l.sampled||t.#xe(),p={...a,onProgress:a.onProgress?(g,f,m,y)=>{try{m?.byteLength&&(u&&c.push(m.slice(0)),h+=m.byteLength)}catch{}a.onProgress(g,f,m,y)}:void 0,onSuccess:(g,f,m,y)=>{let v=qr(f),b=null,T=0;try{let B=g?.data;B?.byteLength?(u&&(b=B.slice(0)),T=B.byteLength):h&&(u&&(b=r.join(c)),T=h)}catch{b=null,T=0}l.originSucceeded=!0,a.onSuccess(g,f,m,y),t.#M(y,v),T?t.#r("origin-loaded",()=>t.#tt(l,b,T)):t.#r("origin-empty",()=>t.#z(l))},onError:(...g)=>{t.#r("origin-error",()=>t.#z(l)),a.onError(...g)},onTimeout:(...g)=>{t.#r("origin-timeout",()=>t.#z(l)),a.onTimeout(...g)}};return a.onAbort&&(p.onAbort=(...g)=>{t.#r("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,h)=>c+h.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}#Qe(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||Gi)(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.#et(o)),o}catch(t){return this.#o("begin-race",t),null}}async#et(e){if(e.keyPromise=Nt($i.encode(e.keyText)),e.key=await e.keyPromise,this.stopped)return;if(!e.sampled||!this.options.serveOnCellular&&Pt())return e.peerDone=!0,e.skipPeers=!0,this.#r("settle",()=>this.#ee(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.#r("settle",()=>this.#ee(e))}#Q(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#tt(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,Ke(this.originLatencySamples,i-e.t0),e.sampled&&(e.originDigest=await Nt(s)),e.originDone=!0,await e.keyPromise,!this.stopped&&(s&&this.#T(e.key,s),this.#r("settle",()=>this.#ee(e)))}#z(e){e.settled||e.originDone||(e.controller.abort(),e.originDone=!0,e.originFailed=!0,this.#r("settle",()=>this.#ee(e)))}async#ee(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 Nt(e.peerBytes)!==e.originDigest){this.#R(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.#R(e.peerLink,e.requestMs,e.peerBytes.byteLength),this.firstPeerSegmentAtMs===null&&(this.firstPeerSegmentAtMs=Date.now()-this.startedAt),Ke(this.peerLatencySamples,s),t.bytesFromPeers+=e.peerBytes.byteLength,s<=this.options.originFallbackMs?(t.peerInTime+=1,t.peerInTimeBytes+=e.peerBytes.byteLength):t.peerLate+=1}#T(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)}#rt(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||!Pt())}#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#nt(e,t,r=null){if(this.uploadPacer)return this.#st(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 h=xt(i.byteLength),u=r.start*h,p=Math.min(r.end*h,i.byteLength);if(!(ua)return this.#y("session-allowance"),null;let l=[...this.links.values()].filter(h=>h!==e&&(h.outboundInFlight>0||Date.now()-h.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:u}),this.lifecycle.signal,this.options.admissionTimeoutMs)===!0}catch{this.#o("upload-reservation")}if(!h||this.stopped||e.closed||this.options.serve!==!0||!this.options.serveOnCellular&&Pt())return h||(this.uploadQuotaBytes-=o),this.#y(h?"reservation-inactive":"reservation-refused"),null}if(this.counters.bytesUploaded+=o,this.counters.uploadsServed+=1,this.options.testHooks?.corruptUploads){let h=i.slice();return h[h.length>>1]^=255,h}return i}#y(e){this.counters.uploadsRefused+=1,this.uploadRefusalCounters[e]=Ve(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&&Pt()||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(!h())return null;let u=this.admissionChecks.get(e.pubkey)?.ticket??this.admitted.get(e.pubkey)?.ticket;if(this.options.admit&&!await at(()=>this.#x(e.pubkey,u,"upload"),c,this.options.admissionTimeoutMs))return this.#y("admission"),e.close("admission"),null;if(!h())return null;if(this.uploadQuotaBytes+=i.charge,o=!0,this.options.reserveUploadBytes){try{a=await at(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(!h()||this.options.admit&&this.admitted.get(e.pubkey)?.ticket!==u)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#it(){this.coreState="loading";try{let e=await Ni(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.#ot(e)}catch(e){this.coreState="failed",this.options.transferWorkerUrl!==void 0&&(this.transferWorkerState="failed",this.transferWorkerReason="core-failed"),this.#o("core",e)}}async#ot(e){this.transferWorkerState="loading";try{let t=this.options.WorkerImpl,r=await Hi({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.#L();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()}#L(){return this.options.multiHolder===!0&&this.options.mode==="peer-first"&&!!this.core&&!this.core.retired&&this.coreLinks.js===0}#at(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 ot(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,Mi(e,t)}async#lt(){let e=this.options.secretKey||Vt();if(this.pool=new _r(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 Or({pool:this.pool,swarmId:this.options.swarmId,secretKey:e,maxEventAgeSeconds:60}),this.session.onPresence(t=>this.#r("presence",()=>this.#gt(t))),this.session.onSignal(t=>this.#r("signal",()=>this.#mt(t))),this.session.onError(t=>this.#o("session",t)),this.session.start(),this.#V(),this.#k(this.options.presenceIntervalMs,.3,()=>this.#V())}#V(){if(!(!this.session||this.stopped))try{this.session.announcePresence({role:"viewer",transports:[{type:zr,publicKey:this.session.pubkey,...this.#L()?{obj:2}:{}}],have:this.#p()?[...this.held.keys()].slice(-8):[],open:this.#ht(),...this.#ne()?{ticket:this.#ne()}:{}}),this.counters.presenceSent+=1;for(let[e,t]of this.renditions){if(t{this.reannounceTimer=null,this.#V()})}#q(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.#q(t,e.rendition)||e.keys.some(r=>t.have.has(r))))}#Re(e){let t=[...this.links.values()].filter(r=>this.#q(r,e.rendition));return t.length>0&&t.every(r=>this.discovery.stale(e,r.pubkey))}#ct(e){return[...this.links.values()].filter(t=>this.#q(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()||we(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 Qi([...this.links.values()].filter(r=>!t.some(s=>!this.discovery.stale(s,r.pubkey)&&(this.#q(r,s.rendition)||s.keys.some(i=>r.have.has(i))))),{...this.options,banned:this.banned,tier:r=>this.#Ie(r)})}#F(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.#F(t))}#te(){if(this.stopped||this.options.mode!=="peer-first"||(this.#j(),!this.#re()))return;for(let i of this.discovery.contexts.values())this.discovery.rearm(i,()=>this.#ct(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.#F(s))),this.#r("discovery",()=>this.#ie(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 Qi(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}`]++}#ht(){return this.#j(),this.discovery.reserved()?!1:this.#_()||this.links.size>=2&&!!this.#Oe()}#ut(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:zr,requestId:r,payload:s}),this.counters.signalsSent+=1,!0)}catch(i){return this.counters.publishErrors+=1,this.#o("signal-send",i),!1}}#ft(e){return yl(e,this.options)}#pt(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.#te();return}if(!(this.links.has(e)||this.dials.has(e)||this.banned.has(e)||!this.#_()))return this.cooldowns.delete(e),this.#ie(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.#r("referral",()=>this.#ie(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"}#ne(){return we(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(!we(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 at(a=>{try{let l=Xi.includes(r)?r:"other";this.admissionCallCounters[l]=Ve(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,...we(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.#r("admission-refresh",async()=>{await this.#x(e,o.ticket,"refresh")&&o.open!==null&&this.#$(e,o.open)})}),this.admissionChecks.set(e,i),i.promise}async#gt({from:e,payload:t}){if(this.stopped||t.role!=="viewer")return;let r=t.transports.find(l=>l.type===zr);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.#te());let s=this.links.has(e)||this.dials.has(e),i=this.admitted.get(e);i&&we(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.#A();return}if(!s&&(this.#D(e)||!this.#_()||!this.#re())){o&&t.open!==null&&this.#$(e,t.open);return}let a=this.admissionChecks.get(e);if(s&&a){we(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.#A(),!(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.#re())return this.#ie(e)}))}#g(e,t,r,s){try{if(!Fr[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]=Ve(this.transportCounters[t][r]),this.transportRecords.length===64&&(this.transportRecords.shift(),this.transportDropped=Ve(this.transportDropped)),this.transportRecords.push(a)}catch{}}#Ne(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}}#Pe(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,Fr[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))}#se(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{}}#He(e,t,r){!r&&e.discovery&&(this.#F(e.discovery.window,!1),e.discovery=null),e.negotiation&&(e.negotiation.superseded=!0),this.#se(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}#De(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.#r("link-open",()=>this.#yt(e,t,r))},r.addEventListener("open",t.onOpen),r.readyState==="open"&&t.onOpen()}}#Ue(e,t){this.#u(e,t)&&(t.ready=!0,t.channel?.readyState==="open"&&t.onOpen())}async#ie(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.#re()){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.#Pe(!0),s=gl(),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.#He(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.#De(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 Ji(r,1200,o.controller.signal,h=>{i.negotiation===o&&!o.superseded&&this.#Ne(r,"offer",h)}),!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.#ne(),c=this.#ue(e,"offer",s,{sdp:r.localDescription.sdp,peers:this.links.size,...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.#se(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.#te()}async#mt({from:e,payload:t}){if(this.stopped||t.transport!==zr)return;let r=typeof t.payload?.sdp=="string"?t.payload.sdp:"";if(t.type==="answer"){let u=this.dials.get(e);if(!u?.outgoing||u.requestId!==t.requestId||!r)return;let p=u.negotiation;if(p.answerPending)return;if(this.#g(u.pc,"answer-received","authenticated"),!await this.#x(e,we(t.payload.ticket)?t.payload.ticket:null,"answerIncoming")){this.#u(u,p)&&this.#m(u,"failed",0,"admission");return}if(!this.#u(u,p)||!u.outgoing||u.requestId!==t.requestId||p.answerPending)return;p.answerPending=!0,this.#g(u.pc,"answer-admitted","accepted"),u.answerAt=I();try{await this.#fe(u,p,async()=>{await u.pc.setRemoteDescription({type:"answer",sdp:r}),this.#u(u,p)&&(this.#g(u.pc,"remote-installed","answer"),this.#Ue(u,p))})}catch(g){this.#u(u,p)&&(this.#o("answer",g),this.#m(u,"failed"))}return}if(t.type==="reject"){let u=this.dials.get(e);if(!u?.outgoing||u.requestId!==t.requestId)return;let p=this.#ft(t.payload);this.#m(u,"rejected",p.retryAfterMs),this.#$(e,!1),this.#pt(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,we(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.#ut(t.payload?.peers,t.payload?.requestedKey)){this.counters.offersRefused+=1,this.counters.evictionsUnavailable+=1,this.#ue(e,"reject",t.requestId,this.#dt(e));return}let u=this.#Pe(!1);a={pubkey:e,pc:u,startedAt:I(),offerSentAt:I()},this.dials.set(e,a),a.timer=this.#h(this.options.dialTimeoutMs,()=>this.#m(a,"timeout"))}let c=a.pc,h=this.#He(a,t.requestId,!1);l&&this.#g(c,"negotiation","glare-yield"),this.#g(c,"offer-admitted","accepted"),h.onDataChannel=u=>this.#De(a,h,u.channel),c.addEventListener("datachannel",h.onDataChannel);try{await this.#fe(a,h,async()=>{if(l){if(!await this.#x(e,we(t.payload.ticket)?t.payload.ticket:null,"glareBeforeRollback")){this.#u(a,h)&&this.#m(a,"failed",0,"admission");return}if(!this.#u(a,h))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,h)))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,we(t.payload.ticket)?t.payload.ticket:null,"glareAfterRollback")){this.#u(a,h)&&this.#m(a,"failed",0,"admission");return}if(!this.#u(a,h))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,h))return;this.#g(c,"remote-installed","offer");let u=await c.createAnswer();if(!this.#u(a,h)||(await c.setLocalDescription(u),!this.#u(a,h))||(await Ji(c,1200,h.controller.signal,f=>{a.negotiation===h&&!h.superseded&&this.#Ne(c,"answer",f)}),!this.#u(a,h)))return;if(!await this.#x(e,we(t.payload.ticket)?t.payload.ticket:null,"answerBeforeSend")){this.#u(a,h)&&this.#m(a,"failed",0,"admission");return}if(!this.#u(a,h))return;let p=this.#ne(),g=this.#ue(e,"answer",t.requestId,{sdp:c.localDescription.sdp,...p?{ticket:p}:{}});this.#g(c,g?"signal-send":"signal-failed","answer"),g?(this.counters.offersAccepted+=1,this.#Ue(a,h)):this.#m(a,"failed")})}catch(u){this.#u(a,h)&&(this.#o("offer",u),this.#m(a,"failed"))}}async#yt(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.#se(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.#F(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&&Ke(this.signallingSamples,I()-e.offerSentAt);let i=this.#at({pubkey:e.pubkey,pc:e.pc,channel:r,maxSegmentBytes:this.options.maxSegmentBytes,onRequest:(a,l,c)=>this.#nt(a,l,c),onHaveChange:(a,l)=>{for(let c of[...this.haveWaiters])c(l);this.#A()},onScheduleChange:()=>{for(let a of[...this.haveWaiters])a();for(let a of[...this.peerLeaseWaiters])a();this.#A()},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.#r("reannounce",()=>this.#Be()))}});this.links.set(e.pubkey,i),this.#qe(e.pubkey),this.#A(),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 pl(e.pc);this.pairTypes[o]=(this.pairTypes[o]||0)+1;for(let a of[...this.haveWaiters])a()}};var Mh=Object.freeze({version:"0.4.4",sourceCommit:"167b1c971c94456983da28d32dede00cd4c3123b"});export{Si as KIND_SEGMENT_COMMITMENT,ki as commitmentContent,xt as commitmentPieceSize,bl as createHlsSwarm,wr as finalizeEvent,Vt as generateSecretKey,Yt as matchFilter,Mh as relayswarmBuild,_t as segmentMediaContext,$t 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 3ae5743..9744b5d 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/a27c1804455699e9d8c8e5d48928680a3b6ba458 +https://github.com/forgesworn/relayswarm/tree/167b1c971c94456983da28d32dede00cd4c3123b MIT License diff --git a/site/vendor/relayswarm-transfer-worker.js b/site/vendor/relayswarm-transfer-worker.js index 2c127e1..5fbd12a 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 a27c1804455699e9d8c8e5d48928680a3b6ba458. See media-peer-demo.NOTICE.txt. */ +/*! RelaySwarm 0.4.4 transfer worker; public source 167b1c971c94456983da28d32dede00cd4c3123b. 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}; From 89f7e7c3b1d22442ce3c5522a8f0fc985ed64d08 Mon Sep 17 00:00:00 2001 From: TheCryptoDonkey <147930957+TheCryptoDonkey@users.noreply.github.com> Date: Tue, 27 Oct 2026 14:03:48 +0000 Subject: [PATCH 2/3] chore: pin verified origin handoff source followup --- docs/media-showcase.md | 4 ++-- scripts/build-media-peer-demo.mjs | 2 +- site/llms.txt | 2 +- site/vendor/media-peer-demo.NOTICE.txt | 2 +- site/vendor/media-peer-demo.build.json | 8 ++++---- site/vendor/media-peer-demo.js | 4 ++-- site/vendor/relayswarm-core.NOTICE.txt | 2 +- site/vendor/relayswarm-transfer-worker.js | 2 +- 8 files changed, 13 insertions(+), 13 deletions(-) diff --git a/docs/media-showcase.md b/docs/media-showcase.md index eef368d..07d237f 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 `167b1c971c94456983da28d32dede00cd4c3123b` -([source change](https://github.com/forgesworn/relayswarm/commit/167b1c971c94456983da28d32dede00cd4c3123b)). +The player pins RelaySwarm source `f923058503778dea2427a81330da04cce80a95c2` +([source change](https://github.com/forgesworn/relayswarm/commit/f923058503778dea2427a81330da04cce80a95c2)). 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 permits one extra contiguous startup fragment when the diff --git a/scripts/build-media-peer-demo.mjs b/scripts/build-media-peer-demo.mjs index 6b8eb02..f36c847 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 = '167b1c971c94456983da28d32dede00cd4c3123b'; +const SOURCE = 'f923058503778dea2427a81330da04cce80a95c2'; const sha = bytes => createHash('sha256').update(bytes).digest('hex'); const root = fileURLToPath(new URL('../', import.meta.url)); diff --git a/site/llms.txt b/site/llms.txt index 6ff89cf..2eaad8d 100644 --- a/site/llms.txt +++ b/site/llms.txt @@ -7,7 +7,7 @@ - [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 167b1c971c94456983da28d32dede00cd4c3123b (package version 0.4.4), retaining bounded rolling startup planning, sustainable peer waits and range-sized WASM uploads. 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. 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 f923058503778dea2427a81330da04cce80a95c2 (package version 0.4.4), retaining bounded rolling startup planning, sustainable peer waits and range-sized WASM uploads. 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. 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. - [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/vendor/media-peer-demo.NOTICE.txt b/site/vendor/media-peer-demo.NOTICE.txt index b8417cb..cee03fb 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/167b1c971c94456983da28d32dede00cd4c3123b +https://github.com/forgesworn/relayswarm/tree/f923058503778dea2427a81330da04cce80a95c2 MIT License diff --git a/site/vendor/media-peer-demo.build.json b/site/vendor/media-peer-demo.build.json index 5a976b3..c1076da 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": "167b1c971c94456983da28d32dede00cd4c3123b", + "sourceCommit": "f923058503778dea2427a81330da04cce80a95c2", "version": "0.4.4", - "sourceArchiveSha256": "f3cd9621efe6e6bc9dde9df078738fd5821f0a9030baba1b85351330cb8ff94d", + "sourceArchiveSha256": "0f5953fbe800cef0e2b1be891a251b5ecbb5610b957d123ac6fab61e8f6f644f", "packageLockSha256": "18a91b8d697ebcab1d259d4de876167dcbd4d47fc3c82196d179c4c490adca4a", "bundle": "media-peer-demo.js", - "bundleSha256": "a3b50af45602e5455f35faa60884becd18354d21f0fa57f46c84c8043e347654", + "bundleSha256": "fba69c6941b377b9e209a6d7a292535422f68fd068c16b340cfcf1ee4b74f96f", "bundleBytes": 260708, "transferWorker": { "file": "relayswarm-transfer-worker.js", "bytes": 7074, - "sha256": "7391dad0c29956401ac9aba155e04cfa12ddc9317c366c2a09e9831d6d046f9d", + "sha256": "548e4205bd2594fdf5a86d6d1800fa566f49c380e15c425e764a3863b0b19ca2", "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 f40d710..a4cf1cf 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 167b1c971c94456983da28d32dede00cd4c3123b. See media-peer-demo.NOTICE.txt. */ +/*! RelaySwarm 0.4.4; public source f923058503778dea2427a81330da04cce80a95c2. See media-peer-demo.NOTICE.txt. */ function Zn(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 Xn(n){return{samples:n.length,offsetSeconds:n.length?Math.round(Math.max(...n)/1e3):null}}function Dt(n){return n instanceof Uint8Array||ArrayBuffer.isView(n)&&n.constructor.name==="Uint8Array"}function He(n,e=""){if(!Number.isSafeInteger(n)||n<0){let t=e&&`"${e}" `;throw new Error(`${t}expected integer >= 0, got ${n}`)}}function se(n,e,t=""){let r=Dt(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");He(n.outputLen),He(n.blockLen)}function Et(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 Qn(n,e){se(n,void 0,"digestInto() output");let t=e.outputLen;if(n.length='+t)}function Ge(...n){for(let e=0;e>>e}var es=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",to=Array.from({length:256},(n,e)=>e.toString(16).padStart(2,"0"));function De(n){if(se(n),es)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 Oe(n){if(typeof n!="string")throw new Error("hex string expected, got "+typeof n);if(es)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 rs=n=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,n])});function ns(n,e,t){return n&e^~n&t}function ss(n,e,t){return n&e^n&t^e&t}var or=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=ir(this.buffer)}update(e){Et(this),se(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 u=o;uh.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u>>3,m=ze(g,17)^ze(g,19)^g>>>10;tt[u]=m+tt[u-7]+f+tt[u-16]|0}let{A:r,B:s,C:i,D:o,E:a,F:l,G:c,H:h}=this;for(let u=0;u<64;u++){let p=ze(a,6)^ze(a,11)^ze(a,25),g=h+p+ns(a,l,c)+ro[u]+tt[u]|0,m=(ze(r,2)^ze(r,13)^ze(r,22))+ss(r,s,i)|0;h=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,h=h+this.H|0,this.set(r,s,i,o,a,l,c,h)}roundClean(){Ge(tt)}destroy(){this.set(0,0,0,0,0,0,0,0),Ge(this.buffer)}},Vr=class extends Kr{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=ts(()=>new Vr,rs(1));var Gr=BigInt(0),$r=BigInt(1);function Ut(n,e=""){if(typeof n!="boolean"){let t=e&&`"${e}" `;throw new Error(t+"expected boolean, got type="+typeof n)}return n}function is(n){if(typeof n=="bigint"){if(!ar(n))throw new Error("positive bigint expected, got "+n)}else He(n);return n}function zt(n){let e=is(n).toString(16);return e.length&1?"0"+e:e}function os(n){if(typeof n!="string")throw new Error("hex string expected, got "+typeof n);return n===""?Gr:BigInt("0x"+n)}function rt(n){return os(De(n))}function Yr(n){return os(De(no(se(n)).reverse()))}function lr(n,e){He(e),n=is(n);let t=Oe(n.toString(16).padStart(e*2,"0"));if(t.length!==e)throw new Error("number too large");return t}function Zr(n,e){return lr(n,e).reverse()}function no(n){return Uint8Array.from(n)}function as(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 ar=n=>typeof n=="bigint"&&Gr<=n;function so(n,e,t){return ar(n)&&ar(e)&&ar(t)&&e<=n&&nGr;n>>=$r,e+=1);return e}var qt=n=>($r<new Uint8Array(y),s=Uint8Array.of(),i=Uint8Array.of(0),o=Uint8Array.of(1),a=1e3,l=r(n),c=r(n),h=0,u=()=>{l.fill(1),c.fill(0),h=0},p=(...y)=>t(c,Se(l,...y)),g=(y=s)=>{c=p(i,y),l=p(),y.length!==0&&(c=p(o,y),l=p())},f=()=>{if(h++>=a)throw new Error("drbg: tried max amount of iterations");let y=0,v=[];for(;y{u(),g(y);let b;for(;!(b=v(f()));)g();return u(),b}}function Ft(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 Jr(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 Le=BigInt(0),Re=BigInt(1),gt=BigInt(2),ds=BigInt(3),fs=BigInt(4),ps=BigInt(5),io=BigInt(7),gs=BigInt(8),oo=BigInt(9),ms=BigInt(16);function qe(n,e){let t=n%e;return t>=Le?t:e+t}function Ne(n,e,t){let r=n;for(;e-- >Le;)r*=r,r%=t;return r}function hs(n,e){if(n===Le)throw new Error("invert: expected non-zero number");if(e<=Le)throw new Error("invert: expected positive modulus, got "+e);let t=qe(n,e),r=e,s=Le,i=Re,o=Re,a=Le;for(;t!==Le;){let c=r/t,h=r%t,u=s-o*c,p=i-a*c;r=t,t=h,s=o,i=a,o=u,a=p}if(r!==Re)throw new Error("invert: does not exist");return qe(s,e)}function en(n,e,t){if(!n.eql(n.sqr(e),t))throw new Error("Cannot find square root")}function ys(n,e){let t=(n.ORDER+Re)/fs,r=n.pow(e,t);return en(n,r,e),r}function ao(n,e){let t=(n.ORDER-ps)/gs,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 en(n,a,e),a}function lo(n){let e=At(n),t=bs(n),r=t(e,e.neg(e.ONE)),s=t(e,r),i=t(e,e.neg(r)),o=(n+io)/ms;return(a,l)=>{let c=a.pow(l,o),h=a.mul(c,r),u=a.mul(c,s),p=a.mul(c,i),g=a.eql(a.sqr(h),l),f=a.eql(a.sqr(u),l);c=a.cmov(c,h,g),h=a.cmov(p,u,f);let m=a.eql(a.sqr(h),l),y=a.cmov(c,h,m);return en(a,y,l),y}}function bs(n){if(n1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return ys;let i=s.pow(r,e),o=(e+Re)/gt;return function(l,c){if(l.is0(c))return c;if(us(l,c)!==1)throw new Error("Cannot find square root");let h=t,u=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===h)throw new Error("Cannot find square root");let y=Re<(r[s]="function",r),e);return Ft(n,t),n}function uo(n,e,t){if(tLe;)t&Re&&(r=n.mul(r,s)),s=n.sqr(s),t>>=Re;return r}function cr(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 us(n,e){let t=(n.ORDER-Re)/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 fo(n,e){e!==void 0&&He(e);let t=e!==void 0?e:n.toString(2).length,r=Math.ceil(t/8);return{nBitLength:t,nByteLength:r}}var Qr=class{ORDER;BITS;BYTES;isLE;ZERO=Le;ONE=Re;_lengths;_sqrt;_mod;constructor(e,t={}){if(e<=Le)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}=fo(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 qe(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return Le<=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?Yr(e):rt(e);if(a&&(l=qe(l,o)),!t&&!this.isValid(l))throw new Error("invalid field element: outside of range 0..ORDER");return l}invertBatch(e){return cr(this,e)}cmov(e,t,r){return r?t:e}};function At(n,e={}){return new Qr(n,e)}function ws(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 rn(n){let e=ws(n);return e+Math.ceil(e/2)}function hr(n,e,t=!1){se(n);let r=n.length,s=ws(e),i=rn(e);if(r<16||r1024)throw new Error("expected "+i+"-1024 bytes of input, got "+r);let o=t?Yr(n):rt(n),a=qe(o,e-Re)+Re;return t?Zr(a,s):lr(a,s)}var kt=BigInt(0),mt=BigInt(1);function jt(n,e){let t=e.negate();return n?t:e}function an(n,e){let t=cr(n.Fp,e.map(r=>r.Z));return e.map((r,s)=>n.fromAffine(r.toAffine(t[s])))}function Es(n,e){if(!Number.isSafeInteger(n)||n<=0||n>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+n)}function nn(n,e){Es(n,e);let t=Math.ceil(e/n)+1,r=2**(n-1),s=2**n,i=qt(n),o=BigInt(n);return{windows:t,windowSize:r,mask:i,maxNumber:s,shiftBy:o}}function vs(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,h=c+Math.abs(a)-1,u=a===0,p=a<0,g=e%2!==0;return{nextN:l,offset:h,isZero:u,isNeg:p,isNegF:g,offsetF:c}}var sn=new WeakMap,As=new WeakMap;function on(n){return As.get(n)||1}function xs(n){if(n!==kt)throw new Error("invalid wNAF")}var ur=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>kt;)t&mt&&(r=r.add(s)),s=s.double(),t>>=mt;return r}precomputeWindow(e,t){let{windows:r,windowSize:s}=nn(t,this.bits),i=[],o=e,a=o;for(let l=0;lkt||r>kt;)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 Ss(n,e,t){if(e){if(e.ORDER!==n)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return tn(e),e}else return At(n,{isLE:t})}function Ms(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>kt))throw new Error(`CURVE.${l} must be positive bigint`)}let s=Ss(e.p,t.Fp,r),i=Ss(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 dr(n,e){return function(r){let s=n(r);return{secretKey:s,publicKey:e(s)}}}var fr=class{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,t){if(pt(e),se(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 fr(n,e).update(t).digest();nt.create=(n,e)=>new fr(n,e);var Bs=(n,e)=>(n+(n>=0?e:-e)/Rs)/e;function po(n,e,t){let[[r,s],[i,o]]=e,a=Bs(o*n,t),l=Bs(-s*n,t),c=n-a*r-l*i,h=-a*s-l*o,u=c=g||h=g)throw new Error("splitScalar (endomorphism): failed, k="+n);return{k1neg:u,k1:c,k2neg:p,k2:h}}function cn(n){if(!["compact","recovered","der"].includes(n))throw new Error('Signature format must be "compact", "recovered", or "der"');return n}function ln(n,e){let t={};for(let r of Object.keys(e))t[r]=n[r]===void 0?e[r]:n[r];return Ut(t.lowS,"lowS"),Ut(t.prehash,"prehash"),t.format!==void 0&&cn(t.format),t}var hn=class extends Error{constructor(e=""){super(e)}},st={Err:hn,_tlv:{encode:(n,e)=>{let{Err:t}=st;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=zt(r);if(s.length/2&128)throw new t("tlv.encode: long form length too big");let i=r>127?zt(s.length/2|128):"";return zt(n)+i+s+e},decode(n,e){let{Err:t}=st,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 h of c)o=o<<8|h;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}=st;if(n{let{X:A,Y:x,Z:R}=d;if(r.eql(R,r.ONE))return{x:A,y:x};let P=d.is0();w==null&&(w=P?r.ONE:r.inv(R));let N=r.mul(A,w),M=r.mul(x,w),H=r.mul(R,w);if(P)return{x:r.ZERO,y:r.ZERO};if(!r.eql(H,r.ONE))throw new Error("invZ was invalid");return{x:N,y:M}}),L=Jr(d=>{if(d.is0()){if(e.allowInfinityPoint&&!r.is0(d.Y))return;throw new Error("bad point: ZERO")}let{x:w,y:A}=d.toAffine();if(!r.isValid(w)||!r.isValid(A))throw new Error("bad point: x or y not field elements");if(!y(w,A))throw new Error("bad point: equation left != right");if(!d.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function U(d,w,A,x,R){return A=new C(r.mul(A.X,d),A.Y,A.Z),w=jt(x,w),A=jt(R,A),w.add(A)}class C{static BASE=new C(i.Gx,i.Gy,r.ONE);static ZERO=new C(r.ZERO,r.ONE,r.ZERO);static Fp=r;static Fn=s;X;Y;Z;constructor(w,A,x){this.X=T("x",w),this.Y=T("y",A,!0),this.Z=T("z",x),Object.freeze(this)}static CURVE(){return i}static fromAffine(w){let{x:A,y:x}=w||{};if(!w||!r.isValid(A)||!r.isValid(x))throw new Error("invalid affine point");if(w instanceof C)throw new Error("projective point not allowed");return r.is0(A)&&r.is0(x)?C.ZERO:new C(A,x,r.ONE)}static fromBytes(w){let A=C.fromAffine(f(se(w,void 0,"point")));return A.assertValidity(),A}static fromHex(w){return C.fromBytes(Oe(w))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(w=8,A=!0){return O.createCache(this,w),A||this.multiply(pr),this}assertValidity(){L(this)}hasEvenY(){let{y:w}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(w)}equals(w){B(w);let{X:A,Y:x,Z:R}=this,{X:P,Y:N,Z:M}=w,H=r.eql(r.mul(A,M),r.mul(P,R)),D=r.eql(r.mul(x,M),r.mul(N,R));return H&&D}negate(){return new C(this.X,r.neg(this.Y),this.Z)}double(){let{a:w,b:A}=i,x=r.mul(A,pr),{X:R,Y:P,Z:N}=this,M=r.ZERO,H=r.ZERO,D=r.ZERO,q=r.mul(R,R),ee=r.mul(P,P),j=r.mul(N,N),V=r.mul(R,P);return V=r.add(V,V),D=r.mul(R,N),D=r.add(D,D),M=r.mul(w,D),H=r.mul(x,j),H=r.add(M,H),M=r.sub(ee,H),H=r.add(ee,H),H=r.mul(M,H),M=r.mul(V,M),D=r.mul(x,D),j=r.mul(w,j),V=r.sub(q,j),V=r.mul(w,V),V=r.add(V,D),D=r.add(q,q),q=r.add(D,q),q=r.add(q,j),q=r.mul(q,V),H=r.add(H,q),j=r.mul(P,N),j=r.add(j,j),q=r.mul(j,V),M=r.sub(M,q),D=r.mul(j,ee),D=r.add(D,D),D=r.add(D,D),new C(M,H,D)}add(w){B(w);let{X:A,Y:x,Z:R}=this,{X:P,Y:N,Z:M}=w,H=r.ZERO,D=r.ZERO,q=r.ZERO,ee=i.a,j=r.mul(i.b,pr),V=r.mul(A,P),re=r.mul(x,N),ae=r.mul(R,M),ge=r.add(A,x),ne=r.add(P,N);ge=r.mul(ge,ne),ne=r.add(V,re),ge=r.sub(ge,ne),ne=r.add(A,R);let pe=r.add(P,M);return ne=r.mul(ne,pe),pe=r.add(V,ae),ne=r.sub(ne,pe),pe=r.add(x,R),H=r.add(N,M),pe=r.mul(pe,H),H=r.add(re,ae),pe=r.sub(pe,H),q=r.mul(ee,ne),H=r.mul(j,ae),q=r.add(H,q),H=r.sub(re,q),q=r.add(re,q),D=r.mul(H,q),re=r.add(V,V),re=r.add(re,V),ae=r.mul(ee,ae),ne=r.mul(j,ne),re=r.add(re,ae),ae=r.sub(V,ae),ae=r.mul(ee,ae),ne=r.add(ne,ae),V=r.mul(re,ne),D=r.add(D,V),V=r.mul(pe,ne),H=r.mul(ge,H),H=r.sub(H,V),V=r.mul(ge,re),q=r.mul(pe,q),q=r.add(q,V),new C(H,D,q)}subtract(w){return this.add(w.negate())}is0(){return this.equals(C.ZERO)}multiply(w){let{endo:A}=e;if(!s.isValidNot0(w))throw new Error("invalid scalar: out of range");let x,R,P=N=>O.cached(this,N,M=>an(C,M));if(A){let{k1neg:N,k1:M,k2neg:H,k2:D}=$(w),{p:q,f:ee}=P(M),{p:j,f:V}=P(D);R=ee.add(V),x=U(A.beta,q,j,N,H)}else{let{p:N,f:M}=P(w);x=N,R=M}return an(C,[x,R])[0]}multiplyUnsafe(w){let{endo:A}=e,x=this;if(!s.isValid(w))throw new Error("invalid scalar: out of range");if(w===Xe||x.is0())return C.ZERO;if(w===Mt)return x;if(O.hasCache(this))return this.multiply(w);if(A){let{k1neg:R,k1:P,k2neg:N,k2:M}=$(w),{p1:H,p2:D}=ks(C,x,P,M);return U(A.beta,H,D,R,N)}else return O.unsafe(x,w)}toAffine(w){return S(this,w)}isTorsionFree(){let{isTorsionFree:w}=e;return o===Mt?!0:w?w(C,this):O.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:w}=e;return o===Mt?this:w?w(C,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(w=!0){return Ut(w,"isCompressed"),this.assertValidity(),g(C,this,w)}toHex(w=!0){return De(this.toBytes(w))}toString(){return``}}let F=s.BITS,O=new ur(C,e.endo?Math.ceil(F/2):F);return C.BASE.precompute(8),C}function Ls(n){return Uint8Array.of(n?2:3)}function _s(n,e){return{secretKey:e.BYTES,publicKey:1+n.BYTES,publicKeyUncompressed:1+2*n.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function mo(n,e={}){let{Fn:t}=n,r=e.randomBytes||Ye,s=Object.assign(_s(n.Fp,t),{seed:rn(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:y}=s;try{let v=g.length;return f===!0&&v!==m||f===!1&&v!==y?!1:!!n.fromBytes(g)}catch{return!1}}function a(g=r(s.seed)){return hr(se(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:y}=s;if(!Dt(g)||"_lengths"in t&&t._lengths||f===m)return;let v=se(g,void 0,"key").length;return v===m||v===y}function h(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 y=t.fromBytes(g);return n.fromBytes(f).multiply(y).toBytes(m)}let u={isValidSecretKey:i,isValidPublicKey:o,randomSecretKey:a},p=dr(a,l);return Object.freeze({getPublicKey:l,getSharedSecret:h,keygen:p,Point:n,utils:u,lengths:s})}function Os(n,e,t={}){pt(e),Ft(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),t=Object.assign({},t);let r=t.randomBytes||Ye,s=t.hmac||((A,x)=>nt(e,A,x)),{Fp:i,Fn:o}=n,{ORDER:a,BITS:l}=o,{keygen:c,getPublicKey:h,getSharedSecret:u,utils:p,lengths:g}=mo(n,t),f={prehash:!0,lowS:typeof t.lowS=="boolean"?t.lowS:!0,format:"compact",extraEntropy:!1},m=a*Rs>Mt;return A>x}function v(A,x){if(!o.isValidNot0(x))throw new Error(`invalid signature ${A}: out of range 1..Point.Fn.ORDER`);return x}function b(){if(m)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function T(A,x){cn(x);let R=g.signature,P=x==="compact"?R:x==="recovered"?R+1:void 0;return se(A,P)}class B{r;s;recovery;constructor(x,R,P){if(this.r=v("r",x),this.s=v("s",R),P!=null){if(b(),![0,1,2,3].includes(P))throw new Error("invalid recovery id");this.recovery=P}Object.freeze(this)}static fromBytes(x,R=f.format){T(x,R);let P;if(R==="der"){let{r:D,s:q}=st.toSig(se(x));return new B(D,q)}R==="recovered"&&(P=x[0],R="compact",x=x.subarray(1));let N=g.signature/2,M=x.subarray(0,N),H=x.subarray(N,N*2);return new B(o.fromBytes(M),o.fromBytes(H),P)}static fromHex(x,R){return this.fromBytes(Oe(x),R)}assertRecovery(){let{recovery:x}=this;if(x==null)throw new Error("invalid recovery id: must be present");return x}addRecoveryBit(x){return new B(this.r,this.s,x)}recoverPublicKey(x){let{r:R,s:P}=this,N=this.assertRecovery(),M=N===2||N===3?R+a:R;if(!i.isValid(M))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let H=i.toBytes(M),D=n.fromBytes(Se(Ls((N&1)===0),H)),q=o.inv(M),ee=S(se(x,void 0,"msgHash")),j=o.create(-ee*q),V=o.create(P*q),re=n.BASE.multiplyUnsafe(j).add(D.multiplyUnsafe(V));if(re.is0())throw new Error("invalid recovery: point at infinify");return re.assertValidity(),re}hasHighS(){return y(this.s)}toBytes(x=f.format){if(cn(x),x==="der")return Oe(st.hexFromSig(this));let{r:R,s:P}=this,N=o.toBytes(R),M=o.toBytes(P);return x==="recovered"?(b(),Se(Uint8Array.of(this.assertRecovery()),N,M)):Se(N,M)}toHex(x){return De(this.toBytes(x))}}let $=t.bits2int||function(x){if(x.length>8192)throw new Error("input is too large");let R=rt(x),P=x.length*8-l;return P>0?R>>BigInt(P):R},S=t.bits2int_modN||function(x){return o.create($(x))},L=qt(l);function U(A){return ls("num < 2^"+l,A,Xe,L),o.toBytes(A)}function C(A,x){return se(A,void 0,"message"),x?se(e(A),void 0,"prehashed message"):A}function F(A,x,R){let{lowS:P,prehash:N,extraEntropy:M}=ln(R,f);A=C(A,N);let H=S(A),D=o.fromBytes(x);if(!o.isValidNot0(D))throw new Error("invalid private key");let q=[U(D),U(H)];if(M!=null&&M!==!1){let re=M===!0?r(g.secretKey):M;q.push(se(re,void 0,"extraEntropy"))}let ee=Se(...q),j=H;function V(re){let ae=$(re);if(!o.isValidNot0(ae))return;let ge=o.inv(ae),ne=n.BASE.multiply(ae).toAffine(),pe=o.create(ne.x);if(pe===Xe)return;let Q=o.create(ge*o.create(j+pe*D));if(Q===Xe)return;let me=(ne.x===pe?0:2)|Number(ne.y&Mt),et=Q;return P&&y(Q)&&(et=o.neg(Q),me^=1),new B(pe,et,m?void 0:me)}return{seed:ee,k2sig:V}}function O(A,x,R={}){let{seed:P,k2sig:N}=F(A,x,R);return cs(e.outputLen,o.BYTES,s)(P,N).toBytes(R.format)}function d(A,x,R,P={}){let{lowS:N,prehash:M,format:H}=ln(P,f);if(R=se(R,void 0,"publicKey"),x=C(x,M),!Dt(A)){let D=A instanceof B?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+D)}T(A,H);try{let D=B.fromBytes(A,H),q=n.fromBytes(R);if(N&&D.hasHighS())return!1;let{r:ee,s:j}=D,V=S(x),re=o.inv(j),ae=o.create(V*re),ge=o.create(ee*re),ne=n.BASE.multiplyUnsafe(ae).add(q.multiplyUnsafe(ge));return ne.is0()?!1:o.create(ne.x)===ee}catch{return!1}}function w(A,x,R={}){let{prehash:P}=ln(R,f);return x=C(x,P),B.fromBytes(A,"recovered").recoverPublicKey(x).toBytes()}return Object.freeze({keygen:c,getPublicKey:h,getSharedSecret:u,utils:p,lengths:g,Point:n,sign:O,verify:d,recoverPublicKey:w,Signature:B,hash:e})}var yr={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},yo={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},bo=BigInt(0),un=BigInt(2);function wo(n){let e=yr.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,h=c*c*n%e,u=Ne(h,t,e)*h%e,p=Ne(u,t,e)*h%e,g=Ne(p,un,e)*c%e,f=Ne(g,s,e)*g%e,m=Ne(f,i,e)*f%e,y=Ne(m,a,e)*m%e,v=Ne(y,l,e)*y%e,b=Ne(v,a,e)*m%e,T=Ne(b,t,e)*h%e,B=Ne(T,o,e)*f%e,$=Ne(B,r,e)*c%e,S=Ne($,un,e);if(!gr.eql(gr.sqr(S),n))throw new Error("Cannot find square root");return S}var gr=At(yr.p,{sqrt:wo}),yt=Ts(yr,{Fp:gr,endo:yo}),Ns=Os(yt,Fe),Is={};function mr(n,...e){let t=Is[n];if(t===void 0){let r=Fe(as(n));t=Se(r,r),Is[n]=t}return Fe(Se(t,...e))}var fn=n=>n.toBytes(!0).slice(1),pn=n=>n%un===bo;function dn(n){let{Fn:e,BASE:t}=yt,r=e.fromBytes(n),s=t.multiply(r);return{scalar:pn(s.y)?r:e.neg(r),bytes:fn(s)}}function Ps(n){let e=gr;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);pn(s)||(s=e.neg(s));let i=yt.fromAffine({x:n,y:s});return i.assertValidity(),i}var Wt=rt;function Hs(...n){return yt.Fn.create(Wt(mr("BIP0340/challenge",...n)))}function Cs(n){return dn(n).bytes}function vo(n,e,t=Ye(32)){let{Fn:r}=yt,s=se(n,void 0,"message"),{bytes:i,scalar:o}=dn(e),a=se(t,32,"auxRand"),l=r.toBytes(o^Wt(mr("BIP0340/aux",a))),c=mr("BIP0340/nonce",l,i,s),{bytes:h,scalar:u}=dn(c),p=Hs(h,i,s),g=new Uint8Array(64);if(g.set(h,0),g.set(r.toBytes(r.create(u+p*o)),32),!Ds(g,s,i))throw new Error("sign: Invalid signature produced");return g}function Ds(n,e,t){let{Fp:r,Fn:s,BASE:i}=yt,o=se(n,64,"signature"),a=se(e,void 0,"message"),l=se(t,32,"publicKey");try{let c=Ps(Wt(l)),h=Wt(o.subarray(0,32));if(!r.isValidNot0(h))return!1;let u=Wt(o.subarray(32,64));if(!s.isValidNot0(u))return!1;let p=Hs(s.toBytes(h),fn(c),a),g=i.multiplyUnsafe(u).add(c.multiplyUnsafe(s.neg(p))),{x:f,y:m}=g.toAffine();return!(g.is0()||!pn(m)||f!==h)}catch{return!1}}var Bt=(()=>{let t=(r=Ye(48))=>hr(r,yr.n);return{keygen:dr(t,Cs),getPublicKey:Cs,sign:vo,verify:Ds,Point:yt,utils:{randomSecretKey:t,taggedHash:mr,lift_x:Ps,pointToBytes:fn},lengths:{secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:64,seed:48}}})();var tc=new TextDecoder("utf-8"),xo=new TextEncoder;function So(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 Rt=Symbol("verified"),Eo=n=>n instanceof Object;function Ao(n){if(!Eo(n)||typeof n.kind!="number"||typeof n.content!="string"||typeof n.created_at!="number"||typeof n.pubkey!="string"||!So(n.pubkey)||!Array.isArray(n.tags))return!1;for(let e=0;e{function t(r,...s){if(Ee(r,void 0,"key"),!To)throw new Error("Non little-endian hardware is not yet supported");if(n.nonceLength!==void 0){let h=s[0];Ee(h,n.varSizeNonce?void 0:n.nonceLength,"nonce")}let i=n.tagLength;i&&s[1]!==void 0&&Ee(s[1],void 0,"AAD");let o=e(r,...s),a=(h,u)=>{if(u!==void 0){if(h!==2)throw new Error("cipher output not supported");Ee(u,void 0,"output")}},l=!1;return{encrypt(h,u){if(l)throw new Error("cannot encrypt() twice with same key + nonce");return l=!0,Ee(h),a(o.encrypt.length,u),o.encrypt(h,u)},decrypt(h,u){if(Ee(h),i&&h.lengthUint8Array.from(n.split(""),e=>e.charCodeAt(0)),_o=Ws("expand 16-byte k"),Oo=Ws("expand 32-byte k"),Io=Je(_o),Co=Je(Oo);function Y(n,e){return n<>>32-e}function bn(n){return n.byteOffset%4===0}var Er=64,No=16,Ks=2**32-1,js=Uint32Array.of();function Po(n,e,t,r,s,i,o,a){let l=s.length,c=new Uint8Array(Er),h=Je(c),u=bn(s)&&bn(i),p=u?Je(s):js,g=u?Je(i):js;for(let f=0;f=Ks)throw new Error("arx: counter overflow");let m=Math.min(Er,l-f);if(u&&m===Er){let y=f/4;if(f%4!==0)throw new Error("arx: invalid block position");for(let v=0,b;v{Ee(a,void 0,"key"),Ee(l,void 0,"nonce"),Ee(c,void 0,"data");let p=c.length;if(h===void 0&&(h=new Uint8Array(p)),Ee(h,void 0,"output"),xr(u),u<0||u>=Ks)throw new Error("arx: counter overflow");if(h.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 h=0;h<8;h++)this.pad[h]=ke(e,16+2*h)}process(e,t,r=!1){let s=r?0:2048,{h:i,r:o}=this,a=o[0],l=o[1],c=o[2],h=o[3],u=o[4],p=o[5],g=o[6],f=o[7],m=o[8],y=o[9],v=ke(e,t+0),b=ke(e,t+2),T=ke(e,t+4),B=ke(e,t+6),$=ke(e,t+8),S=ke(e,t+10),L=ke(e,t+12),U=ke(e,t+14),C=i[0]+(v&8191),F=i[1]+((v>>>13|b<<3)&8191),O=i[2]+((b>>>10|T<<6)&8191),d=i[3]+((T>>>7|B<<9)&8191),w=i[4]+((B>>>4|$<<12)&8191),A=i[5]+($>>>1&8191),x=i[6]+(($>>>14|S<<2)&8191),R=i[7]+((S>>>11|L<<5)&8191),P=i[8]+((L>>>8|U<<8)&8191),N=i[9]+(U>>>5|s),M=0,H=M+C*a+F*(5*y)+O*(5*m)+d*(5*f)+w*(5*g);M=H>>>13,H&=8191,H+=A*(5*p)+x*(5*u)+R*(5*h)+P*(5*c)+N*(5*l),M+=H>>>13,H&=8191;let D=M+C*l+F*a+O*(5*y)+d*(5*m)+w*(5*f);M=D>>>13,D&=8191,D+=A*(5*g)+x*(5*p)+R*(5*u)+P*(5*h)+N*(5*c),M+=D>>>13,D&=8191;let q=M+C*c+F*l+O*a+d*(5*y)+w*(5*m);M=q>>>13,q&=8191,q+=A*(5*f)+x*(5*g)+R*(5*p)+P*(5*u)+N*(5*h),M+=q>>>13,q&=8191;let ee=M+C*h+F*c+O*l+d*a+w*(5*y);M=ee>>>13,ee&=8191,ee+=A*(5*m)+x*(5*f)+R*(5*g)+P*(5*p)+N*(5*u),M+=ee>>>13,ee&=8191;let j=M+C*u+F*h+O*c+d*l+w*a;M=j>>>13,j&=8191,j+=A*(5*y)+x*(5*m)+R*(5*f)+P*(5*g)+N*(5*p),M+=j>>>13,j&=8191;let V=M+C*p+F*u+O*h+d*c+w*l;M=V>>>13,V&=8191,V+=A*a+x*(5*y)+R*(5*m)+P*(5*f)+N*(5*g),M+=V>>>13,V&=8191;let re=M+C*g+F*p+O*u+d*h+w*c;M=re>>>13,re&=8191,re+=A*l+x*a+R*(5*y)+P*(5*m)+N*(5*f),M+=re>>>13,re&=8191;let ae=M+C*f+F*g+O*p+d*u+w*h;M=ae>>>13,ae&=8191,ae+=A*c+x*l+R*a+P*(5*y)+N*(5*m),M+=ae>>>13,ae&=8191;let ge=M+C*m+F*f+O*g+d*p+w*u;M=ge>>>13,ge&=8191,ge+=A*h+x*c+R*l+P*a+N*(5*y),M+=ge>>>13,ge&=8191;let ne=M+C*y+F*m+O*f+d*g+w*p;M=ne>>>13,ne&=8191,ne+=A*u+x*h+R*c+P*l+N*a,M+=ne>>>13,ne&=8191,M=(M<<2)+M|0,M=M+H|0,H=M&8191,M=M>>>13,D+=M,i[0]=H,i[1]=D,i[2]=q,i[3]=ee,i[4]=j,i[5]=V,i[6]=re,i[7]=ae,i[8]=ge,i[9]=ne}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){gn(this),Ee(e),e=Tt(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 Ho(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 Vs=Ho(n=>new vn(n));function Ys(n,e,t,r,s,i=20){let o=n[0],a=n[1],l=n[2],c=n[3],h=e[0],u=e[1],p=e[2],g=e[3],f=e[4],m=e[5],y=e[6],v=e[7],b=s,T=t[0],B=t[1],$=t[2],S=o,L=a,U=l,C=c,F=h,O=u,d=p,w=g,A=f,x=m,R=y,P=v,N=b,M=T,H=B,D=$;for(let ee=0;ee{n.update(e);let t=e.length%16;t&&n.update(zo.subarray(t))},qo=new Uint8Array(32);function Gs(n,e,t,r,s){s!==void 0&&Ee(s,void 0,"AAD");let i=n(e,t,qo),o=Fs(r.length,s?s.length:0,!0),a=Vs.create(i);s&&$s(a,s),$s(a,r),a.update(o);let l=a.digest();return Qe(i,o),l}var Zs=n=>(e,t,r)=>({encrypt(i,o){let a=i.length;o=yn(a+16,o,!1),o.set(i);let l=o.subarray(0,-16);n(e,t,l,l,1);let c=Gs(n,e,t,l,r);return o.set(c,a),Qe(c),o},decrypt(i,o){o=yn(i.length-16,o,!1);let a=i.subarray(0,-16),l=i.subarray(-16),c=Gs(n,e,t,a,r);if(!Sr(l,c))throw new Error("invalid tag");return o.set(i.subarray(0,-16)),n(e,t,o,o,1),Qe(c),o}}),wc=mn({blockSize:64,nonceLength:12,tagLength:16},Zs(Ar)),vc=mn({blockSize:64,nonceLength:24,tagLength:16},Zs(Uo));function Js(n,e,t){return pt(n),t===void 0&&(t=new Uint8Array(n.outputLen)),nt(n,t,e)}var xn=Uint8Array.of(0),Xs=Uint8Array.of();function Qs(n,e,t,r=32){pt(n),He(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=Xs:se(t,void 0,"info");let o=new Uint8Array(i*s),a=nt.create(n,e),l=a._cloneInto(),c=new Uint8Array(a.outputLen);for(let h=0;htypeof t=="string"):e.every(t=>Number.isSafeInteger(t)):!1}function Gt(n,e){if(typeof e!="string")throw new Error(`${n}: string expected`);return!0}function An(n){if(!Number.isSafeInteger(n))throw new Error(`invalid integer: ${n}`)}function En(n){if(!Array.isArray(n))throw new Error("array expected")}function kr(n,e){if(!ri(!0,e))throw new Error(`${n}: array of strings expected`)}function jo(n,e){if(!ri(!1,e))throw new Error(`${n}: array of numbers expected`)}function Wo(...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 Ko(n){let e=typeof n=="string"?n.split(""):n,t=e.length;kr("alphabet",e);let r=new Map(e.map((s,i)=>[s,i]));return{encode:s=>(En(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=>(En(s),s.map(i=>{Gt("alphabet.decode",i);let o=r.get(i);if(o===void 0)throw new Error(`Unknown letter: "${i}". Allowed: ${n}`);return o}))}}function Vo(n=""){return Gt("join",n),{encode:e=>(kr("join.decode",e),e.join(n)),decode:e=>(Gt("join.decode",e),e.split(n))}}function $o(n,e="="){return An(n),Gt("padding",e),{encode(t){for(kr("padding.encode",t);t.length*n%8;)t.push(e);return t},decode(t){kr("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 ni=(n,e)=>e===0?n:ni(e,n%e),Mr=(n,e)=>n+(e-ni(n,e)),Sn=(()=>{let n=[];for(let e=0;e<40;e++)n.push(2**e);return n})();function ei(n,e,t,r){if(En(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(Mr(e,t)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${t} carryBits=${Mr(e,t)}`);let s=0,i=0,o=Sn[e],a=Sn[t]-1,l=[];for(let c of n){if(An(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 h=Sn[i];if(h===void 0)throw new Error("invalid carry");s&=h-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 Go(n,e=!1){if(An(n),n<=0||n>32)throw new Error("radix2: bits should be in (0..32]");if(Mr(8,n)>32||Mr(n,8)>32)throw new Error("radix2: carry overflow");return{encode:t=>{if(!ti(t))throw new Error("radix2.encode input should be Uint8Array");return ei(Array.from(t),8,n,!e)},decode:t=>(jo("radix2.decode",t),Uint8Array.from(ei(t,n,8,e)))}}var Yo=typeof Uint8Array.from([]).toBase64=="function"&&typeof Uint8Array.fromBase64=="function",Zo=(n,e)=>{Gt("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"})},kn=Yo?{encode(n){return Fo(n),n.toBase64()},decode(n){return Zo(n,!1)}}:Wo(Go(6),Ko("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),$o(6),Vo(""));var Xo=new TextDecoder("utf-8"),si=new TextEncoder,Mn=1,Bn=4294967295,Rn=65536;function Jo(n,e){let t=Ns.getSharedSecret(n,Oe("02"+e)).subarray(1,33);return Js(Fe,t,si.encode("nip44-v2"))}function ii(n,e){let t=Qs(Fe,n,e,76);return{chacha_key:t.subarray(0,32),chacha_nonce:t.subarray(32,44),hmac_key:t.subarray(44,76)}}function Tn(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 Qo(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 ea(n){if(!Number.isSafeInteger(n)||nBn)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 oi(n){let e=si.encode(n),t=e.length;if(tBn)throw new Error("invalid plaintext size: must be between 1 and 4294967295 bytes");let r=t>=Rn?Se(new Uint8Array([0,0]),ea(t)):Qo(t),s=new Uint8Array(Tn(t)-t);return Se(r,e,s)}function ai(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),rBn||i.length!==r||n.length!==s+Tn(r))throw new Error("invalid padding");return Xo.decode(i)}function li(n,e,t){if(t.length!==32)throw new Error("AAD associated data must be 32 bytes");let r=Se(t,e);return nt(Fe,n,r)}function ta(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=kn.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 ra(n,e,t=Ye(32)){let{chacha_key:r,chacha_nonce:s,hmac_key:i}=ii(e,t),o=oi(n),a=Ar(r,s,o),l=li(i,a,t);return kn.encode(Se(new Uint8Array([2]),t,a,l))}function na(n,e){let{nonce:t,ciphertext:r,mac:s}=ta(n),{chacha_key:i,chacha_nonce:o,hmac_key:a}=ii(e,t),l=li(a,r,t);if(!Sr(l,s))throw new Error("invalid MAC");let c=Ar(i,o,r);return ai(c)}var Br={utils:{getConversationKey:Jo,calcPaddedLen:Tn,pad:oi,unpad:ai},encrypt:ra,decrypt:na};function Yt(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 Rr=3,Tr=24170,Ln=24171,Lr="x",Zt=/^[0-9a-f]{64}$/u,sa=/^[a-z0-9](?:[a-z0-9-]{0,31})$/u,ia=1*1024*1024,ci=16*1024,oa=64*1024,hi=8*1024,aa=2*1024,ui=30,la=64,ca=256,di=new TextEncoder;function bt(n){return typeof n=="string"?di.encode(n).byteLength:n instanceof ArrayBuffer||ArrayBuffer.isView(n)?n.byteLength:di.encode(String(n)).byteLength}function ha(n){return Array.from(globalThis.crypto.getRandomValues(new Uint8Array(n)),e=>e.toString(16).padStart(2,"0")).join("")}function yi(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 _n=n=>Math.min(Number.MAX_SAFE_INTEGER,n);function fi(n,e){let t=yi(n,e);return t.length===1?t[0]:null}function pi(n){let e=JSON.parse(n);if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Expected a JSON object.");return e}function it(n){return typeof n=="string"&&sa.test(n)}function gi(n){return typeof n=="string"&&n.length>=8&&n.length<=64&&/^[a-zA-Z0-9_-]+$/u.test(n)}function ua(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 _r=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(ua))],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.#n().finally(()=>{this.connecting=null}),this.connecting)}async#n(){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,h]of this.subscriptions)i.send(JSON.stringify(["REQ",c,h]));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)>ia)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&&!Yt(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=ha(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()}},Or=class{#n=null;#t=null;#e=new Map;#s=null;constructor({pool:e,swarmId:t,secretKey:r=Vt(),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=Us(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={[`#${Lr}`]:[this.swarmId],since:Math.floor(Date.now()/1e3)-2};try{this.#t=this.pool.onRelayOpen?.(t=>{if(!this.started||!this.#n)return;let r=Math.floor(Date.now()/1e3)-this.#n.created_at;if(!Number.isFinite(r)||!Number.isFinite(this.maxEventAgeSeconds)||r<-ui||r>this.maxEventAgeSeconds){this.#n=null;return}t(this.#n)}),this.subscriptionId=this.pool.subscribe({...e,since:Math.floor(Date.now()/1e3)-this.maxEventAgeSeconds,kinds:[Tr]}),this.subscriptionIds.push(this.subscriptionId),this.subscriptionIds.push(this.pool.subscribe({...e,kinds:[Ln],"#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.#n=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&&!we(i))throw new Error("Invalid presence ticket.");if(!it(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=>!Zt.test(c)))throw new Error("Invalid object hash list.");let o=t.map(c=>{if(!c||typeof c!="object"||!it(c.type)||!Zt.test(c.publicKey)||c.obj!==void 0&&!mi(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:Rr,role:e,transports:o,have:[...new Set(r)],...s===void 0?{}:{open:!!s},...i===void 0?{}:{ticket:i}});if(bt(a)>ci)throw new Error("Presence payload is too large.");let l=wr({kind:Tr,created_at:Math.floor(Date.now()/1e3),tags:[[Lr,this.swarmId]],content:a},this.secretKey);return this.pool.publish(l),this.#n=JSON.parse(JSON.stringify(l)),l}sendSignal(e,{type:t,transport:r,requestId:s,payload:i={}}={}){if(!Zt.test(e))throw new Error("Invalid signal recipient.");if(!it(t)||!it(r)||!gi(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:Rr,type:t,transport:r,requestId:s,payload:i});if(bt(o)>hi)throw new Error("Signal payload is too large.");let a=Br.encrypt(o,this.#r(e)),l=wr({kind:Ln,created_at:Math.floor(Date.now()/1e3),tags:[[Lr,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 h=!1;try{h=t(c)}catch(u){clearTimeout(l),e.delete(a),o(u);return}h&&(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!==Tr&&e.kind!==Ln||!Number.isSafeInteger(e.created_at)||fi(e,Lr)!==this.swarmId)return;let t=Math.floor(Date.now()/1e3)-e.created_at;if(t<-ui){this.clock.aheadRejected=_n(this.clock.aheadRejected+1),this.clock.maxAheadSeconds=Math.max(this.clock.maxAheadSeconds,_n(-t));return}if(t>this.maxEventAgeSeconds){this.clock.staleRejected=_n(this.clock.staleRejected+1);return}try{e.kind===Tr?this.#c(e):this.#o(e)}catch{}}#c(e){if(bt(e.content)>ci||yi(e,"p").length!==0)return;let t=pi(e.content);if(t.v!==Rr||!it(t.role)||!Array.isArray(t.transports)||t.transports.length>8||!Array.isArray(t.have)||t.have.length>32||t.have.some(o=>!Zt.test(o)))return;let r=t.transports.map(o=>{if(!o||typeof o!="object"||!it(o.type)||!Zt.test(o.publicKey))throw new Error("Invalid transport capability.");return{type:o.type,publicKey:o.publicKey,...mi(o.obj)?{obj:o.obj}:{}}}),s=typeof t.open=="boolean"?t.open:null,i=we(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)>oa||fi(e,"p")!==this.pubkey)return;let t=Br.decrypt(e.content,this.#r(e.pubkey));if(bt(t)>hi)return;let r=pi(t);r.v!==Rr||!it(r.type)||!it(r.transport)||!gi(r.requestId)||!r.payload||typeof r.payload!="object"||Array.isArray(r.payload)||(this.clock.signalAges.length>=la&&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}))}#r(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=Br.utils.getConversationKey(this.secretKey,e),this.#e.size>=ca&&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.#n=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 mi(n){return Number.isSafeInteger(n)&&n>=1&&n<=15}function we(n){return typeof n=="string"&&n.length>0&&bt(n)<=aa}var On=/^[0-9a-f]{64}$/u,bi="relayswarm-abandon";var wi=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"]),ot=class{static ABANDON_REASON=bi;#n=!1;constructor({pubkey:e,pc:t,channel:r,maxSegmentBytes:s,onRequest:i,onHaveChange:o,onScheduleChange:a,onClose:l,onUploadCancelled:c,maxQueuedRequests:h=4,drainTimeoutMs:u=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=h,this.drainTimeoutMs=u,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=(h,u=null)=>{if(!l&&(l=!0,typeof i=="function"))try{let p=null;if(Number.isFinite(a))try{p=performance.now()-a}catch{}let g=u?.received??0,f=Number.isFinite(u?.firstByteAt)&&Number.isFinite(a)?u.firstByteAt-a:null;i({outcome:h,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:u?u.size>=0:!1,draining:u?.draining===!0,closeReason:wi.has(this.closeReason)?this.closeReason:null})}catch{}};if(this.closed||this.pending||r?.aborted){let h=Promise.resolve(null);return c(this.closed?"closed":this.pending?"busy":"abort"),h}return new Promise(h=>{let u=this.nextId++,p=b=>{clearTimeout(this.pending.timer),r?.removeEventListener("abort",m),h(b)},g=(b,T=b?"payload":"none",B=!0)=>{if(this.pending?.id!==u)return;let $=this.pending,S=$.draining;p(b),this.pending=null,b&&(this.lastDeliveredAt=Date.now()),S&&!this.closed&&this.onScheduleChange?.(this),B&&c(T,$)},f=b=>{let T=this.pending;if(!T||T.id!==u||T.draining)return;let B=!1;try{B=this.channel.ordered===!0&&this.channel.maxRetransmits===null&&this.channel.maxPacketLifeTime===null&&this.channel.readyState==="open"}catch{}let $=b!=="request-abort"?"timeout":r?.reason===bi?"abandoned":"abort";if(!B){g(null,$,!1);try{this.close(b)}finally{c($,T)}return}T.draining=!0,T.parts.length=0,p(null),T.timer=setTimeout(()=>{this.pending===T&&T.draining&&this.close(b)},this.drainTimeoutMs),c($,T),T.cancelled=this.#t({t:"cancel",id:u})},m=()=>f("request-abort"),y=()=>f("request-timeout"),v=typeof o=="function"?b=>{try{o(b.received,b.size,Number.isFinite(a)?b.firstByteAt-a:null)}catch{}}:null;this.pending={id:u,key:e,expectedSize:s,size:-1,parts:[],chunks:0,received:0,firstByteAt:null,progress:v,draining:!1,cancelled:!1,finish:g,timer:setTimeout(y,Math.max(1,t))},r?.addEventListener("abort",m,{once:!0}),this.#t({t:"want",id:u,k:e})||g(null,"send-error")})}close(e="host"){if(!this.closed){this.closed=!0,this.closeReason=wi.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"&&On.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"||!On.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.#n?"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.#n=!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 vi(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 da=n=>vi(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 da(this.recentFirstBytes)}rate(){let e=this.firstByteMs(),t=e===null?[]:this.recentRates.filter(({flowMs:r})=>r>=e*3);return vi((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),h=a.length&&(!c.length||this.turn===0&&i>=100);this.turn=(this.turn+1)%4;let u=h?a:c.length?c:l,p=f=>{let m=this.summary(f);return h?m.lastSelected:(this.estimate(f,s)??1e3)*(1+m.failureRate*4)},g=u.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 Xt=/^[0-9a-f]{64}$/u,fa=4,pa=1e4,ga=8,xi=2e4,Lt=class{constructor(e=()=>Date.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||!Xt.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){!Xt.test(e)||!Array.isArray(t)||(this.candidates.delete(e),this.candidates.set(e,{pubkey:e,have:[...new Set(t.filter(s=>typeof s=="string"&&Xt.test(s)))].slice(-8),ticket:we(r)?r:null,at:this.clock()}),this.candidates.size>64&&this.candidates.delete(this.candidates.keys().next().value))}#n(e){return!!(e&&this.contexts.get(e.mediaType)===e)}holderMiss(e,t,r){if(!this.#n(e)||!Xt.test(t)||!Xt.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>=ga&&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.#n(e)&&e.holders.delete(t)}stale(e,t){let r=this.#n(e)?e.holders.get(t):null;return!!r&&r.misses>=fa&&this.clock()-r.firstMissAt>=pa}forget(e){for(let t of this.contexts.values())t.holders.delete(e)}spent(e){return e.spentAt!==null}rearm(e,t){if(!this.#n(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:xi,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 at(n,e,t){return new Promise((r,s)=>{let i=new AbortController,o=!1,a,l=(h,u,p=!1,g=u)=>{o||(o=!0,clearTimeout(a),e?.removeEventListener("abort",c),p&&i.abort(g),h?r(u):s(u))},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(h=>l(!0,h),h=>l(!1,h))})}var Si=24172,ma=24173,ya=24174,In=/^[0-9a-f]{64}$/u,ba="relayswarm-segment-v1",wa="relayswarm-segment-v2",va="relayswarm-segment-v3",Ei={1:ba,2:wa,3:va},xa=new TextEncoder,Sa=512,vt=new Map;function Ir(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=Kt(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):$t(e)?(vt.size>=Sa&&vt.delete(vt.keys().next().value),vt.set(r,!0),!0):!1}function Cr(n){return xa.encode(JSON.stringify(n)).length<=16*1024}function lt(n,e){let t=n.tags.filter(r=>r[0]===e);return t.length===1&&t[0].length===2?t[0][1]:null}function Cn(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 Ai(n){return n.v===3?3:n.v===2?2:1}function ki(n){let e=Ai(n),t=e>=2;return JSON.stringify({domain:Ei[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 Ea(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 Aa(n){return JSON.stringify({domain:"relayswarm-commitment-revocation-v1",v:1,streamEventId:n.streamEventId,swarmId:n.swarmId,delegationId:n.delegationId})}function Nr(n){try{return n.kind===30311&&Cr(n)&&Ir(n)&&typeof lt(n,"d")=="string"&&n.tags.some(e=>e.length===3&&e[0]==="relayswarm"&&e[1]==="redistribute"&&e[2]==="1")}catch{return!1}}function ka(n,{streamEvent:e,swarmId:t,revokedDelegationIds:r=[],delegationRevocations:s=[]},i=Date.now()){try{let o=Math.floor(i/1e3);if(!Nr(e)||!n||!Cr(n)||n.kind!==ma||n.pubkey!==e.pubkey||!Ir(n)||lt(n,"x")!==t||lt(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!==Ea(a)||a.domain!=="relayswarm-commitment-delegation-v1"||a.v!==1||a.streamEventId!==e.id||a.swarmId!==t||!In.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=>!(Cn(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||!Cr(l)||l.kind!==ya||l.pubkey!==e.pubkey||!Number.isSafeInteger(l.created_at)||l.created_ato+30||!Ir(l)||lt(l,"e")!==n.id||lt(l,"x")!==t)continue;let c=JSON.parse(l.content);if(l.content===Aa(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 _t(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))||!Cn(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||!Cn(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 Mi(n,{streamEvent:e,swarmId:t,key:r,context:s,maxSegmentBytes:i,delegation:o,revokedDelegationIds:a,delegationRevocations:l},c=Date.now()){try{let h=Math.floor(c/1e3);if(!Number.isSafeInteger(i)||i<1||i>16*1024*1024||!Nr(e)||!n||n.kind!==Si||!Cr(n)||!Number.isSafeInteger(n.created_at)||n.created_at>h+30||n.created_at=2;if(n.content!==ki(u)||u.domain!==Ei[p]||![1,2,3].includes(u.v)||u.streamEventId!==e.id||u.swarmId!==t||u.key!==r||u.sequence!==s.frag.sn||u.discontinuity!==(s.frag.cc??0)||u.part!==(s.part?.index??null)||!Number.isSafeInteger(u.sequence)||u.sequence<0||!Number.isSafeInteger(u.discontinuity)||u.discontinuity<0||u.part!==null&&(!Number.isSafeInteger(u.part)||u.part<0)||!In.test(u.sha256)||!Number.isSafeInteger(u.size)||u.size<1||u.size>i||!Number.isSafeInteger(u.expiresAt)||u.expiresAt<=h||u.expiresAt>h+300||p===3&&(u.pieceSize!==xt(u.size)||!Array.isArray(u.pieces)||u.pieces.length!==Math.ceil(u.size/u.pieceSize)||u.pieces.some(f=>typeof f!="string"||!In.test(f))))return null;if(g){let f=_t(s);if(!f||u.rendition!==f.playlist||u.playlist!==f.playlist||u.mediaType!==f.mediaType||JSON.stringify(u.encryption)!==JSON.stringify(f.encryption))return null}else if(u.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=ka(o,{streamEvent:e,swarmId:t,revokedDelegationIds:a,delegationRevocations:l},c);if(!f||n.pubkey!==f.delegatePubkey||lt(n,"delegation")!==o.id||n.created_atf.expiresAt||!f.renditions.includes(u.rendition)||!f.mediaTypes.includes(g?u.mediaType:"main")||u.part!==null&&!f.allowParts||u.size>f.maxSegmentBytes)return null}return u}catch{return null}}var Bi=new TextEncoder,Ma=new TextDecoder;function Ri(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 Ba=(n,e)=>new Uint8Array(n.memory.buffer,n.rs_result_ptr(),e);function Ti(n,{size:e,sha256:t,pieces:r,deadline:s,maxHolders:i,originReserveMs:o,peerOnly:a=!1},l,c){if(l()||!Ra.every(h=>typeof n[h]=="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 h=Ri(n,Bi.encode(JSON.stringify({sha256:t,pieces:r,...a?{peerOnly:!0}:{}})),(u,p)=>n.rs_xfer_new(e,s,i,o,u,p));return h?new Pn(n,h,l,c,a):null}catch(h){return c(h),null}}var Ra=["rs_xfer_new","rs_xfer_call","rs_xfer_free"],Jt={start:0,delivered:1,failed:2,tick:3,state:4,progress:5},Pn=class{#n;#t;#e;#s;#d;constructor(e,t,r,s,i=!1){this.#n=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.#n.rs_xfer_capabilities=="function"&&!!(this.#n.rs_xfer_capabilities()&1)}catch{}let l=new Set(o),c=a?t:t.filter(([h])=>!l.has(h));return this.#i(Jt.start,e,-1,0,0,Bi.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(Jt.delivered,e,t,r.start,r.end,s)}failed(e,t){return this.#i(Jt.failed,e,t,0,0,Nn)}tick(e){return this.#i(Jt.tick,e,-1,0,0,Nn)}progress(e,t,r){return this.#i(Jt.progress,e,t,r,0,Nn)}free(){if(this.#t===null)return;let e=this.#t;if(this.#t=null,!this.#e())try{this.#n.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.#n;try{let l=Ri(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=Ba(a,l),h=new DataView(c.buffer,c.byteOffset,l).getUint32(0,!0),u=JSON.parse(Ma.decode(c.subarray(4,4+h))),p=l>4+h?c.slice(4+h):null;return{commands:u.c.map(f=>f.p?{...f,range:{start:f.p[0],end:f.p[1]}}:f),next:u.next,late:u.late,finished:u.finished,verified:u.verified??null,bytes:p}}catch(l){return this.#s(l),null}}},Nn=new Uint8Array(0);var Me={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},Ue={sendText:1,sendBinary:2,closed:3,report:4,resolved:5,haveChanged:6,scheduleChanged:7,serveRequest:8,uploadCancelled:9,progress:10,serveRange:11},Ta=128*1024,La=32*1024,_a=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"]),ct=new TextEncoder,Ot=new TextDecoder,Hn=new Uint8Array(0),Dn=()=>{try{return globalThis.performance.now()}catch{return null}},Li=n=>{let e=Math.trunc(Math.max(1,n));return e>=1&&e<=2**31-1?e:1},Pr=class n{get supportsRanges(){return!this.closed}static ABANDON_REASON=ot.ABANDON_REASON;#n;#t;#e=-1;#s=null;#d=null;#i=0;#c=!1;#o=!1;#r=new Map;#h=null;#k=!1;#M=0;constructor({pubkey:e,pc:t,channel:r,maxSegmentBytes:s,onRequest:i,onHaveChange:o,onScheduleChange:a,onClose:l,onUploadCancelled:c,maxQueuedRequests:h=4,drainTimeoutMs:u=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=h,this.drainTimeoutMs=u,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.#n=p,this.#i=this.openedAt,this.#t=p.newLink(s,h,u,this.#l(),this.openedAt),p.links.add(this),r.binaryType="arraybuffer",r.bufferedAmountLowThreshold=La,r.addEventListener("message",g=>{if(this.closed)return;let{data:f}=g;typeof f=="string"?this.#a(Me.text,{bytes:ct.encode(f)}):this.#a(Me.binary,{bytes:f instanceof ArrayBuffer?new Uint8Array(f):ArrayBuffer.isView(f)?new Uint8Array(f.buffer,f.byteOffset,f.byteLength):Hn})}),r.addEventListener("close",()=>this.close("channel-close")),r.addEventListener("error",()=>this.close("channel-error")),r.addEventListener("bufferedamountlow",()=>{this.closed||this.#a(Me.bufferedLow,{a:this.#B()})}),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(Me.sendHave,{bytes:ct.encode(JSON.stringify([...e]))})}sendHaveChange(e=[],t=[]){this.closed||this.#a(Me.sendHaveChange,{bytes:ct.encode(JSON.stringify({add:[...e],del:[...t]}))})}sendContribution(e,t){this.closed||this.#a(Me.sendContribution,{a:e?1:0,bytes:ct.encode(JSON.stringify(typeof t=="string"?t:null))})}sendFetching(e,t=0){this.closed||this.#a(Me.sendFetching,{a:t,bytes:ct.encode(String(e))})}request(e,t,{signal:r,expectedSize:s,onResult:i,onProgress:o,range:a}={}){let l=Dn(),c=!1,h=(p,g=null)=>{if(!c&&(c=!0,typeof i=="function"))try{let f=null;if(Number.isFinite(l)){let v=Dn();Number.isFinite(v)&&(f=v-l)}let m=g?.receivedBytes??0,y=Number.isFinite(u?.firstByteAt)&&Number.isFinite(l)?u.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(y)&&y>=0?y:null,metadataReceived:g?.metadataReceived===!0,draining:g?.draining===!0,closeReason:_a.has(this.closeReason)?this.closeReason:null})}catch{}},u=null;if(this.closed||this.#c||r?.aborted){let p=Promise.resolve(null);return h(this.closed?"closed":this.#c?"busy":"abort"),p}return new Promise(p=>{let g=()=>{u.id!==null&&!this.closed&&this.#a(Me.abort,{a:u.id,b:r?.reason===n.ABANDON_REASON?1:0})};u={id:null,firstByteAt:null,settled:!1,report:h,onProgress:o,startedAt:l,settle:m=>{u.settled||(u.settled=!0,r?.removeEventListener("abort",g),p(m))}};let f=s===void 0?NaN:Number.isSafeInteger(s)&&s>=0?s:-1;this.#h=u;try{a?this.#a(Me.requestRange,{a:Li(t),b:a.objectSize,bytes:ct.encode(JSON.stringify([String(e),a.start,a.end]))}):this.#a(Me.request,{a:Li(t),b:f,bytes:ct.encode(String(e))})}finally{this.#h=null}if(u.id===null){u.settle(null),h("closed");return}u.settled||r?.addEventListener("abort",g,{once:!0})})}close(e="host"){if(!this.closed){if(this.#t===null)return this.#b("host");this.#a(Me.close,{bytes:ct.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.#n.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.#r.values())t.settle(null),t.report("closed");this.#r.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=Hn,now:i=this.#f()}={}){if(this.#t===null)return;let o=this.#n.call(this.#t,e,i,(this.#S()?1:0)|(this.#l()?2:0),t,r,s);o&&this.#A(o)}#A({header:e,events:t}){let[r,s,i,o,a,l,c,h,u,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=h,this.lastServedAt=u,this.lastDeliveredAt=p,!Number.isNaN(f)&&this.#h&&(this.#h.id=f,this.#r.set(f,this.#h)),r!==this.#e&&this.#w(r),this.closed&&this.announced.clear();let y=++this.#M;for(let v of t)this.#O(v);if(y===this.#M&&this.#t!==null&&(this.#Y(g),m===1&&this.#B()<=Ta))return this.#a(Me.bufferedLow,{a:this.#B()});this.closed&&!this.#o&&this.#t!==null&&(this.#n.free(this.#t),this.#t=null,this.#n.links.delete(this),this.#I())}#w(e){let t=this.#n.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 Ue.sendText:{if(this.#k)return;let i=Ot.decode(t);try{this.channel.send(i)}catch{this.#k=!0,this.close("send-error")}return}case Ue.sendBinary:{if(this.#k)return;try{this.channel.send(t)}catch{this.#k=!0,this.close("serve-error")}return}case Ue.closed:{this.closeReason=Ot.decode(t),this.#I();try{this.channel.close()}catch{}try{this.pc.close()}catch{}this.onClose?.(this);return}case Ue.report:{let i=JSON.parse(Ot.decode(t)),o=i.id===null?this.#h:this.#r.get(i.id);if(!o)return;o.report(i.outcome,i),o.settled&&i.id!==null&&this.#r.delete(i.id);return}case Ue.resolved:{let i=Number.isNaN(r)?this.#h:this.#r.get(r);if(!i)return;i.settle(t);return}case Ue.haveChanged:{let i=JSON.parse(Ot.decode(t));this.onHaveChange?.(this,i);return}case Ue.scheduleChanged:{this.onScheduleChange?.(this);return}case Ue.serveRequest:case Ue.serveRange:{let i,o;if(e===Ue.serveRange){let[a,l,c]=JSON.parse(Ot.decode(t));i=a,o={start:l,end:c}}else i=Ot.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 Ue.uploadCancelled:{this.onUploadCancelled?.(this,s(0));return}case Ue.progress:{let i=s(0),o=s(1);for(let a of this.#r.values())if(!a.settled&&(a.firstByteAt===null&&(a.firstByteAt=Dn()),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}.`)}}#B(){try{return Math.max(0,Number(this.channel.bufferedAmount)||0)}catch{return 0}}#v(e,t){if(this.#t===null)return;let r=this.#B(),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(Me.serve,{a:0,b:r});if(s&&t&&this.#n.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(Me.serve,{a:0,b:r}):this.#a(Me.serveRange,{a:i,b:r,bytes:s.subarray(t.start*o,Math.min(i,t.end*o))})}this.#a(Me.serve,{a:s?1:0,b:r,bytes:s??Hn})}#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(Me.tick)},Math.max(0,e-this.#f())))}#I(){this.#s!==null&&globalThis.clearTimeout(this.#s),this.#s=null,this.#d=null}};var Oa=/^[0-9a-f]{64}$/u,oe={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},Ia=6e4,Ca=2e4,Na=new Set([oe.stale,oe.current,oe.valid,oe.live,oe.reserved,oe.suppresses]),Qt=class extends Error{constructor(e){super("Core discovery failed.",{cause:e})}},Hr=class{#n;#t;#e=null;#s=new Map;#d=new Map;#i=new WeakMap;#c=null;#o=null;#r=new WeakMap;#h=new WeakMap;#k=new Map;#M=1;#b=null;#S=null;constructor(e,t,r=()=>Date.now()){this.#n=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(oe.candidates,[]).map(e=>[e.pubkey,e]))}retire(){this.#e||(this.#S=null,this.#e=new Lt(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 Qt))throw r;this.retire();try{this.#t?.(r.cause)}catch{}return t(this.#e)}}#f(e,t){try{let r=this.#n(e,this.clock(),t);if(e===oe.candidates)return r.map(([s,i,o,a])=>({pubkey:s,have:i,ticket:o,at:a}));if(Na.has(e)&&typeof r!="boolean")throw new TypeError(`Core discovery answered operation ${e} with ${typeof r}.`);return r}catch(r){throw new Qt(r)}}#a(e,t){try{let{r,s}=this.#n(e,this.clock(),t);return this.#A(s),r}catch(r){throw new Qt(r)}}#A({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.#r.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.#r.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.#k:this.#h,i=s.get(e);return i===void 0&&t&&s.set(e,i=this.#M++),i}#B(e){let t=this.clock();return this.#S??=this.#f(oe.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(oe.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(oe.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"||!Oa.test(e)||!Array.isArray(t)||this.#l(()=>{this.#S=null,this.#f(oe.hint,[e,t.filter(s=>typeof s=="string"),we(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(oe.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(oe.holderAhead,[this.#w(e),t])},r=>r.holderAhead(e,t))}stale(e,t){return typeof t!="string"?!1:this.#l(()=>this.#f(oe.stale,[this.#w(e),t]),r=>r.stale(e,t))}forget(e){typeof e=="string"&&this.#l(()=>{this.#f(oe.forget,[e])},t=>t.forget(e))}current(e){return this.#l(()=>this.#w(e)!==null&&this.#f(oe.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(oe.current,[this.#w(o)])&&t(o)).map(o=>o.mediaType);return i.length===0?this.#b=null:this.#v(this.#a(oe.choose,[this.#B(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(oe.hinted,[r,this.#B(t)]))},r=>r.hinted(e,t))}begin(e){return this.#l(()=>!e||e!==this.#b?null:(this.#b=null,this.#a(oe.begin,[])===null?null:this.#c?.attempt??null),t=>t.begin(e))}valid(e){return this.#l(()=>{let t=e?this.#r.get(e):void 0;return t!==void 0&&this.#f(oe.valid,[t])},t=>t.valid(e))}replaced(e,t){return this.#l(()=>{let r=e?this.#r.get(e):void 0;return r!==void 0&&this.#a(oe.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.#r.get(e);r!==void 0&&this.#a(oe.allocated,[r,this.#O(t,!0)])},r=>r.allocated(e,t))}abandoned(e){this.#l(()=>{let t=e?this.#r.get(e):void 0;t!==void 0&&this.#a(oe.abandoned,[t])},t=>t.abandoned(e))}failed(e){this.#l(()=>{let t=this.#O(e,!1);t!==void 0&&this.#a(oe.failed,[t])},t=>t.failed(e))}end(e=this.window){return this.#l(()=>!!e&&e===this.#c&&this.#a(oe.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(oe.verified,[t])},t=>t.verified(e))}live(e=this.window){return this.#l(()=>!!e&&e===this.#c&&this.#f(oe.live,[]),t=>t.live(e))}reserved(){return this.#l(()=>this.#f(oe.reserved,[]),e=>e.reserved())}suppresses(e){return typeof e!="string"?!1:this.#l(()=>this.#f(oe.suppresses,[e]),t=>t.suppresses(e))}snapshot(){return this.#l(()=>({...this.#f(oe.snapshot,[]),counters:{...this.counters}}),e=>e.snapshot())}clear(){this.#l(()=>{this.#b=null,this.#S=null,this.#a(oe.clear,[])},e=>e.clear())}};var Pa=0,Ha=1,Da=2,Ua=3,_i=new TextEncoder,Un=new TextDecoder;function za(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:_t(n)}}async function qa(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 Fa=["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"],Oi=13,ja=15,zn=13,Ci=zn*8,Wa=5,It=n=>Number.isNaN(n)?null:n,Ii=(n,e)=>new Float64Array(n.memory.buffer,e,6);function Dr(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 Ur=(n,e)=>new Uint8Array(n.memory.buffer,n.rs_result_ptr(),e);function Ka(n,e){let t=Ur(n,e),r=new DataView(t.buffer,t.byteOffset,e),s=new Array(zn);for(let o=0;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 qn=class{#n;#t;#e=null;#s=new WeakMap;#d=0;constructor(e,t){this.#n=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.#n)}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=>Ii(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 It(this.#o(0))}rate(){return It(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=>It(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=>It(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]=Ii(t,t.rs_sel_summary(this.#c(e)));return{attempts:r,latencyMs:It(s),throughputBytesPerSecond:It(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(u=>!u.closed&&!u.busy&&!r.has(u.pubkey)&&u.have.has(t)),l=a.map(u=>this.#c(u)),c=l.length*4,h=o.rs_alloc(c);try{let u=new DataView(o.memory.buffer,h,c);l.forEach((g,f)=>u.setUint32(f*4,g,!0));let p=o.rs_sel_select(h,l.length,s,i);return p<0?null:a[l.indexOf(p)]}finally{o.rs_free(h,c)}},o=>o.select(e,t,r,s,i))}};async function Ni(n,{onFailure:e}={}){let{instance:t,module:r}=await qa(n),s=t.exports;for(let m of["memory","rs_alloc","rs_free","rs_call","rs_result_ptr",...Fa])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[...h.links])m.die()}},c=m=>{if(!i){l();try{e?.(m)}catch{}}},h={links:new Set,rangeUploads:typeof s.rs_link_serve_range=="function",newLink(m,y,v,b,T){if(i)throw new Error("The core has been retired.");return s.rs_link_new(m,y,v,b?1:0,T)},free(m){if(!i)try{s.rs_link_free(m)}catch(y){c(y)}},call(m,y,v,b,T,B,$){if(i)return null;try{let S=Dr(s,$,(L,U)=>y===ja&&h.rangeUploads?s.rs_link_serve_range(m,v,b,T,B,L,U):s.rs_link_call(m,y,v,b,T,B,L,U));if(S<0||Ss.rs_link_call(m,Oi,0,0,0,0,v,b));if(y<0)throw new Error(`Core link ${m} refused operation ${Oi}.`);return JSON.parse(Un.decode(Ur(s,y)))}catch(y){return c(y),null}}};function u(m,y){let v;try{v=_i.encode(JSON.stringify(y))}catch{return null}let b=Dr(s,v,(T,B)=>s.rs_call(m,T,B));return b<0?null:JSON.parse(Un.decode(Ur(s,b)))}function p(m,y,v){if(i)throw new Error("The core has been retired.");let b=_i.encode(JSON.stringify(v)),T=Dr(s,b,(B,$)=>s.rs_disc_call(m,y,B,$));if(T<0)throw new Error(`Core discovery refused operation ${m}.`);return JSON.parse(Un.decode(Ur(s,T)))}let g=({streamEvent:m,swarmId:y,revokedDelegationIds:v=[],delegationRevocations:b=[]})=>({streamEvent:m,swarmId:y,revokedDelegationIds:v,delegationRevocations:b}),f=Object.freeze({kind:"wasm",validStreamAuthorisation:m=>u(Pa,[m])===!0,verifyCommitmentDelegation:(m,y,v=Date.now())=>u(Ha,[m??null,g(y),v]),verifySegmentCommitment(m,y,v=Date.now()){let b;try{b=za(y.context)}catch{return null}return u(Da,[m??null,{...g(y),key:y.key,context:b,maxSegmentBytes:y.maxSegmentBytes,delegation:y.delegation??null},v])}});return Object.freeze({module:r,verifier:f,playerHint(m){if(i)return null;try{return u(Ua,m)}catch(y){return c(y),null}},retire:l,get retired(){return i},peerSelection(){if(o)throw new Error("This core instance already has a peer selection.");return o=new qn(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 Hr(p,c,m)},peerLink(m){return new Pr(m,h)},transfer(m){return Ti(s,m,()=>i,c)}})}var Va=new Uint8Array(0);var $a=Object.freeze({maxTransfers:2,maxSegmentBytes:16777216,maxActiveBytes:33554432,maxPending:32,maxPendingBytes:33554432,initTimeoutMs:5e3,operationTimeoutMs:5e3}),Ga=Object.freeze({maxTransfers:4,maxSegmentBytes:32*1048576,maxActiveBytes:64*1048576,maxPending:128,maxPendingBytes:64*1048576,initTimeoutMs:3e4,operationTimeoutMs:3e4}),Pi=n=>typeof n=="string"&&n.length===64&&/^[a-f0-9]{64}$/.test(n),je=n=>Number.isSafeInteger(n)&&n>=0,tr=n=>Number.isFinite(n)&&n>=0&&n<=Number.MAX_SAFE_INTEGER,er=n=>n===null||tr(n),Ya=(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||tr(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}},Ct=()=>new DOMException("Core transfer was cancelled.","AbortError");function Za(n={}){let e={};for(let[t,r]of Object.entries($a)){let s=n[t]??r;if(!Number.isSafeInteger(s)||s<1||s>Ga[t])throw new fe("invalid-limits");e[t]=s}return Object.freeze(e)}function Xa(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||!Pi(t.sha256)||!Array.isArray(t.pieces)||t.pieces.length<1||t.pieces.length>256||!t.pieces.every(Pi)||!tr(t.deadline)||!je(t.maxHolders)||t.maxHolders<1||t.maxHolders>32||!tr(t.originReserveMs)||n.peerOnly!==void 0&&typeof n.peerOnly!="boolean")throw new fe("invalid-transfer");return t}function Ja(n,e,t,r=!1){let[s,i,o]=e;if(!tr(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])&&er(l[1])&&er(l[2]))||(r?a.origin!=null:!Array.isArray(a.origin)||a.origin.length!==2||!a.origin.every(er))||!er(a.sharedFirstByteMs??null)||!er(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??((L,U)=>new Worker(L,U)),l;try{l=a(e,{type:"module",name:"relayswarm-transfer"})}catch{throw new fe("worker-unavailable")}let c="loading",h=null,u=0,p=0,g=0,f=0,m=new Map,y=new Map,v=L=>{L.signal?.removeEventListener("abort",L.onAbort),y.get(L.id)===L&&(y.delete(L.id),f-=L.size)},b=(L,U=!0)=>{if(!(c==="stopped"||c==="failed")){c=U?"failed":"stopped",h=L.code??L.name,l.removeEventListener("message",$),l.removeEventListener("error",T),l.removeEventListener("messageerror",T),r?.removeEventListener("abort",B);for(let C of m.values())clearTimeout(C.timer),C.settled||C.reject(L);m.clear(),g=0;for(let C of y.values())C.closed=!0,v(C);try{l.terminate()?.catch?.(()=>{})}catch{}if(U)try{s?.(L)?.catch?.(()=>{})}catch{}}},T=L=>{L?.preventDefault?.(),b(new fe("worker-error"))},B=()=>b(Ct(),!1),$=({data:L})=>{if(!L||L.v!==1||!je(L.id)||!m.has(L.id))return;let U=m.get(L.id);if(m.delete(L.id),g-=U.bytes,clearTimeout(U.timer),L.ok!==!0){let C=new fe(typeof L.error=="string"&&/^[a-z-]{1,40}$/.test(L.error)?L.error:"invalid-response");U.settled||U.reject(C),(L.fatal||L.ok!==!1)&&b(C)}else if(["init","new","free"].includes(U.op)?L.result!==!0:!Ya(L.result,U.size)){let C=new fe("invalid-response");U.settled||U.reject(C),b(C)}else U.settled||U.resolve(L.result)},S=(L,U,C,F=0,O=[],d=!1)=>c==="stopped"||c==="failed"?Promise.reject(new fe("closed")):!d&&m.size>=o.maxPending||g+F>o.maxPendingBytes?Promise.reject(new fe("queue-limit")):new Promise((w,A)=>{let x=++u,R={resolve:w,reject:A,handle:U,bytes:F,op:L,size:y.get(U)?.size??o.maxSegmentBytes,settled:!1,timer:setTimeout(()=>b(new fe(L==="init"?"init-timeout":"operation-timeout")),L==="init"?o.initTimeoutMs:o.operationTimeoutMs)};m.set(x,R),g+=F;try{l.postMessage({v:1,id:x,op:L,handle:U,input:C},O)}catch{b(new fe("worker-message"))}});l.addEventListener("message",$),l.addEventListener("error",T),l.addEventListener("messageerror",T),r?.addEventListener("abort",B,{once:!0}),r?.aborted&&B();try{await S("init",null,{module:n,limits:o})}catch(L){throw b(L),L}if(c!=="loading")throw new fe("closed");return c="ready",Object.freeze({snapshot:()=>({state:c,reason:h,transfers:y.size,activeBytes:f,pending:m.size,pendingBytes:g}),stop:B,async transfer(L,{signal:U}={}){if(c!=="ready")throw new fe("closed");if(U?.aborted)throw Ct();let C=Xa(L,o);if(y.size>=o.maxTransfers||f+C.size>o.maxActiveBytes)throw new fe("transfer-limit");let F={id:++p,size:C.size,closed:!1,signal:U,release:null};y.set(F.id,F),f+=C.size;let O=()=>{if(F.release)return F.release;F.closed=!0;for(let w of m.values())w.handle===F.id&&!w.settled&&(w.settled=!0,w.reject(Ct()));return F.release=S("free",F.id,null,0,[],!0).then(()=>!0,()=>!1).finally(()=>v(F))};F.onAbort=()=>{O()},U?.addEventListener("abort",F.onAbort,{once:!0});try{await S("new",F.id,C)}catch(w){throw F.closed||v(F),w}if(F.closed||U?.aborted)throw O(),Ct();let d=async(w,A)=>{if(F.closed)throw new fe("closed-transfer");try{let x=Ja(w,A,o.maxSegmentBytes,C.peerOnly===!0),R=0,P=[];if(w==="delivered"){if(R=x[3].byteLength,g+R>o.maxPendingBytes)throw new fe("queue-limit");x[3]=x[3].slice(),P=[x[3].buffer]}let N=await S(w,F.id,x,R,P);if(F.closed)throw Ct();return N}catch(x){throw O(),x}};return Object.freeze({start:(w,A)=>d("start",[w,A]),delivered:(w,A,x,R)=>d("delivered",[w,A,x,R]),failed:(w,A)=>d("failed",[w,A]),progress:(w,A,x)=>d("progress",[w,A,x]),tick:w=>d("tick",[w]),free:O,cancel:O,get closed(){return F.closed}})}})}function Di(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 ht(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 Ui(n,e,t,r,{signal:s,onIgnored:i,onResult:o}={}){let a=Di(e,t,r);return!a||typeof n?.Loader!="function"||typeof e?.url!="string"||s?.aborted?(ht(o,s?.aborted?"abort":"invalid-request",t,r),Promise.resolve(null)):new Promise(l=>{let c=null,h=!1,u=(f,m,y=f?.byteLength??null,v=null)=>{if(!h){h=!0,s?.removeEventListener("abort",p);try{c?.destroy?.()}catch{}ht(o,m,t,r,y,v),l(f)}},p=()=>{try{c?.abort?.()}catch{}u(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 u(null,"abort");let m=g(f?.data);if(!m&&!h)try{i?.()}catch{}u(m,m?"payload":"wrong-size",f?.data?.byteLength??null,f?.code)},onError:f=>u(null,s?.aborted?"abort":"error",null,f?.code),onTimeout:()=>u(null,s?.aborted?"abort":"timeout"),onAbort:()=>u(null,"abort")})}catch{u(null,"exception")}})}function Qa(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 zi(n,e,t,{signal:r,onIgnored:s,onResult:i,fetchImpl:o=globalThis.fetch}={}){let a=Di(n,e,t);if(!a||typeof n?.url!="string"||typeof o!="function"||r?.aborted)return ht(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 ht(i,r?.aborted?"abort":"error",e,t),null}let c=(h=null)=>{try{s?.()}catch{}return ht(i,"wrong-size",e,t,h,l.status),null};try{if(l.status!==206||!Qa(l.headers.get("content-range"),a)){try{await l.body?.cancel()}catch{}return l.status===200||l.status===206?c():(ht(i,"error",e,t,null,l.status),null)}let h=new Uint8Array(await l.arrayBuffer());return h.byteLength!==t-e?c(h.byteLength):(ht(i,"payload",e,t,h.byteLength,l.status),h)}catch{return ht(i,r?.aborted?"abort":"error",e,t,null,l?.status),null}}var Te=Symbol("relayswarm-warm-ahead"),We=24*1024*1024,qi=3,Fn=4,rr=8e3,el=100,dt=n=>{let{start:e,duration:t}=n?.context?.frag??{};return Number.isFinite(e)&&e>=0&&Number.isFinite(t)&&t>0&&Number.isFinite(e+t)},jn=(n,e)=>dt(n)&&n.context.frag.start<=e&&en?.key===e?.key&&n?.scope===e?.scope&&dt(n)&&dt(e)&&n.context.frag.start===e.context.frag.start&&n.context.frag.duration===e.context.frag.duration,tl=(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 Fi({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:h=null,startupCommit:u=null,startupRecovery:p=()=>2e3}){let g=!1,f=0,m=null,y=null,v=[],b,T,B=null,$=0,S=new Map,L=new Set,U=new Map,C=new Set,F=new Set,O=new Map,d={enabled:typeof h=="function",state:h?"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},w={started:0,verified:0,rejected:0,cancelled:0,coalesced:0,promotions:0,localReuseBytes:0,verifiedBytes:0,verifiedPeerBytes:0,consumedPeerBytes:0,cacheBytes:0,highWaterBytes:0},A=()=>d.reserved+[...U.values()].reduce((E,k)=>E+k.reserved,0),x=()=>new Set([...S.keys(),...U.keys(),...d.owner?[d.own.key]:[]]).size,R=()=>d.state==="buffering"?Fn:qi,P=E=>U.get(E.key)===E&&!E.finished,N=E=>{let k=S.get(E);k&&(w.cacheBytes-=k.data.byteLength,S.delete(E))},M=(E,k)=>{P(E)&&(E.finished=!0,U.delete(E.key),C.delete(E),m===E&&(m=null),E.reserved=0,E.finish(k),d.checking&&(d.recheck=!0),W(),queueMicrotask(q))},H=E=>{P(E)&&(w.cancelled++,E.cancel(),M(E,null))},D=()=>{(d.state==="idle"||d.state==="buffering")&&Q("cancelled","cleared",!g),d.planningServiceMs=null,f++,v=[],B=null;for(let E of[...U.values()])H(E);for(let E of S.keys())N(E);for(let E of[...F])E(!0)},q=()=>{if(g||m||!l()||!v.length||L.size+C.size>1||!c&&d.state!=="buffering"||d.state==="buffering"&&(!d.permit||d.checking)||d.state==="buffering"&&!jr()||d.state==="buffering"&&x()>=R())return;let E=v.shift();if(S.has(E.key)||U.has(E.key)){queueMicrotask(q);return}for(;x()>=qi&&S.size&&d.state!=="buffering";)N(S.keys().next().value);if(x()>=R())return;let k=new AbortController,z=f,Z=b,_=T,K,J,X,G={...E,reserved:0,finished:!1,waiters:new Set,genuineAt:null,promise:new Promise(te=>{X=te}),noteDemand(){G.genuineAt??=performance.now(),E.context[Te]?.onGenuine?.()},genuine(){if(!P(G))return null;let te=[...G.waiters].find(xe=>xe.pendingTerminal&&Ae(xe.context)?.key===G.key);return te&&G.genuineAt!==null?{at:G.genuineAt,context:te.context}:null},promote(){clearTimeout(J)},finish:te=>X(te),cancel(){k.abort(),clearTimeout(J);try{K?.abort(),K?.destroy()}catch{}}};m=G,U.set(G.key,G),J=setTimeout(()=>H(G),rr),(async()=>{try{let te=await t(E.context,k.signal);if(k.signal.aborted||g||z!==f||!P(G)||!l())return null;if(!te||!Number.isSafeInteger(te.size)||te.size<1||te.size>We)return w.rejected++,null;for(;w.cacheBytes+A()+te.size>We&&S.size&&d.state!=="buffering";)N(S.keys().next().value);if(w.cacheBytes+A()+te.size>We)return w.rejected++,null;if(G.reserved=te.size,!s(A()))return G.reserved=0,w.rejected++,null;w.highWaterBytes=Math.max(w.highWaterBytes,w.cacheBytes+A());let xe=E.context[Te]={peerBytes:0,genuine:()=>G.genuine(),startupDependency:()=>{if(!j()||!P(G)||!l()||!pe(E))return null;try{return me()===null||!j()?null:{at:d.entryAt,deadline:d.deadline,signal:d.controller.signal,context:E.context}}catch{return null}}};K=new n(Z),w.started++;let ue=performance.now(),he=await new Promise(le=>K.load(E.context,_,{onSuccess:(be,ce,Pe,Ce)=>le({response:be,stats:ce,details:Ce,serviceMs:tl(ce,te.size,ue,performance.now())}),onError:(...be)=>le({failure:{name:"onError",args:be,stats:K.stats}}),onTimeout:(...be)=>le({failure:{name:"onTimeout",args:be,stats:K.stats}}),onAbort:(...be)=>le({failure:{name:"onAbort",args:be,stats:K.stats}}),onProgress:be=>{if(be?.loaded>te.size){k.abort();try{K.abort()}catch{}le(null)}}}));if(he?.failure)return k.signal.aborted||g||z!==f||!P(G)?null:(w.rejected++,he);if(!he||k.signal.aborted||g||z!==f||!P(G)||!await r(te,he.response.data,E.context,k.signal))return w.rejected++,null;if(k.signal.aborted||g||z!==f||!P(G))return null;let de=he.response.data;if(de.byteLength!==te.size)return w.rejected++,null;if(G.reserved=0,i?.(te,de,E.context)===!1)return null;let ye={...he,context:E.context,scope:E.scope,data:de,permit:te,peerBytes:xe.peerBytes,accept:xe.accept};return S.set(E.key,ye),w.cacheBytes+=de.byteLength,w.verified++,w.verifiedBytes+=de.byteLength,w.verifiedPeerBytes+=xe.peerBytes,j()&&P(G)&&f===z&&E.scope===y&&pe(E)&&(d.planningServiceMs=he.serviceMs),ye}catch{return k.signal.aborted||w.rejected++,null}finally{clearTimeout(J);try{K?.destroy()}catch{}}})().then(te=>M(G,te))},ee=(E,k,z,Z)=>{B=null;let _=Ae(E);if(!_||g)return null;y!==_.scope&&(y!==null&&D(),y=_.scope),b=k,T=z;let K=[];try{K=e(E).map(Ae).filter(Boolean).filter(X=>X.scope===y).slice(0,2)}catch{}let J=new Set([_.key,...K.map(X=>X.key)]);for(let X of S.keys())J.has(X)||N(X);for(let X of[...U.values()])J.has(X.key)||H(X);return v=K,dt(_)&&K.every(dt)&&(B={own:ae(_),upcoming:K.map(ae),owner:Z}),_},j=()=>{if(d.state!=="buffering"||g||d.revision!==f||d.owner?.pendingTerminal!==d.terminal||d.terminal.settled)return!1;let E=!1;try{E=ut(Ae(d.terminal.context),d.identity)&&ut(Ae(d.own.context),d.identity)&&d.terminal.context.url===d.contextUrl&&d.terminal.context.frag.url===d.fragUrl}catch{}return E?!0:(Q("cancelled","context-changed"),!1)},V=E=>({code:0,text:"RelaySwarm startup buffer unavailable",startupBufferReason:E}),re=E=>e(E.context).map(Ae).filter(Boolean).filter(k=>k.scope===y&&dt(k)).slice(0,2),ae=E=>{let{key:k,scope:z,context:{url:Z,frag:_}}=Ae(E.context);return{key:k,scope:z,context:{url:Z,frag:_,part:null,responseType:"arraybuffer"}}},ge=(E,k)=>({...ae(E),identity:ae(E),parent:ae(k)}),ne=E=>{try{return ut(Ae(E.context),E.identity)&&re(E.parent).some(k=>ut(k,E.identity))}catch{return!1}},pe=E=>{if(!j()||B?.owner!==d.terminal.id)return!1;let k=d.plan.find(z=>ut(z.identity,E));return!!(k&&ne(k))},Q=(E,k,z=!0)=>{if(!["idle","buffering"].includes(d.state))return;let Z=d.owner,_=d.terminal;d.state=E,d.reason=k,E==="failed"&&d.failures++,E==="cancelled"&&d.cancellations++,clearTimeout(d.timer),d.timer=null,clearTimeout(d.poll),d.poll=null,d.controller?.abort(),d.releasePins?.(),d.owner=null,d.terminal=null,d.response=null,d.reserved=0,v=[],d.plan=[],d.cursor=null,d.frozenStart=null,d.planningServiceMs=null;for(let K of[...U.values()])H(K);for(let K of S.keys())N(K);if(!(!Z||!_||_.settled||Z.pendingTerminal!==_)){_.settled=!0,Z.pendingTerminal=null,Z.token++,Z.stats.aborted=!0;try{Z.inner.abort()}catch{}!z||g||(E==="cancelled"?_.callbacks.onAbort?.(Z.stats,_.context,null):_.callbacks.onError?.(V(k),_.context,null,Z.stats))}},me=()=>{let E;try{E=h()}catch{return Q("failed","target-threw"),null}return E===null?(Q("cancelled","target-unavailable"),null):!Number.isFinite(E)||E<0?(Q("failed","invalid-target"),null):(d.targetTime=E,E)},et=()=>{let E;try{E=p(d.own.context)}catch{}return!Number.isFinite(E)||E<0?(Q("failed","invalid-recovery"),null):(d.requiredHeadroomMs=E,E)},Ie=(E,k)=>{if(!j()||d.checking)return;if(d.frozenStart!==null&&E>=d.frozenStart&&(d.frozenStart=null),d.plan.some(_=>!ne(_))||d.cursor&&!ne(d.cursor))return Q("cancelled","context-changed");for(;d.plan.length;){let _=d.plan[0],K=S.get(_.key),J=U.get(_.key);if(_.context.frag.start+_.context.frag.duration>E||J||K&&O.has(K.permit.key)||[...L].some(X=>X.pendingTerminal&&Ae(X.context)?.key===_.key))break;if(!K){if(!d.hopAvailable)return;d.hopAvailable=!1}if(d.cursor=_,d.plan.shift(),v=v.filter(X=>X.key!==_.key),!j()||d.checking)return;N(_.key)}let z=d.plan[0];if(d.verified&&d.response&&d.plan.length===2&&S.size===2&&!m&&!U.size&&!L.size&&!C.size&&jn(z,E)&&d.plan.every(_=>S.has(_.key)&&!O.has(S.get(_.key).permit.key))){let _=St(E);_.end!==null&&(_.end-E)*1e3S.has(_.key)&&!O.has(S.get(_.key).permit.key))){let _=St(E);_.rows.length===d.plan.length+1&&_.end!==null&&(_.end-E)*1e3_.context.frag.start)?d.cursor:_??d.own,J;try{J=re(K)[0]}catch{return Q("cancelled","context-changed")}if(!J)return;let X=K.context.frag.start+K.context.frag.duration;if(Math.abs(J.context.frag.start-X)>.001||J.key===d.own.key||d.plan.some(te=>te.key===J.key))return Q("cancelled","context-changed");let G=ge(J,K);if(J.context.frag.start+J.context.frag.duration<=E){if(!d.hopAvailable)return;d.hopAvailable=!1,d.cursor=G;return}d.plan.push(G),v.push(J)}},jr=()=>{if(!j()||d.checking)return!1;let E=me();if(E===null||!j())return!1;let k=et();if(k===null||!j()||(Ie(E,k),!j()||d.checking||!v.length))return!1;if(d.frozenStart!==null&&EE)return!0;let z=v[0],Z=d.plan.findIndex(_=>_.key===z.key);if(Z<0)return Q("cancelled","context-changed"),!1;if(z.context.frag.start+z.context.frag.duration<=E+(k+(d.planningServiceMs??0))/1e3){if(!d.hopAvailable)return!1;d.hopAvailable=!1,d.cursor=d.plan[Z],d.plan.splice(Z,1),v.shift(),Ie(E,k);let _=v[0]?.context.frag.start;return _>E&&(d.frozenStart=_),!1}return!0},ft=()=>{if(d.poll!==null||!j())return;let E=d.deadline-performance.now();if(E<=0)return Q("failed","deadline");d.poll=setTimeout(()=>{if(d.poll=null,!!j()){if(!d.checking){d.hopAvailable=!0;let k=me();if(k===null||!j())return;if(!l())return Q("cancelled","not-allowed");let z=et();if(z===null||!j()||(Ie(k,z),!j()))return;W(k),queueMicrotask(q)}ft()}},Math.min(el,E))},St=(E,k=null)=>{let z=d.verified&&d.response?[{...d.own,permit:d.permit}]:[],Z=(k??[...z,...S.values()]).filter(X=>X.scope===y&&dt(X)).sort((X,G)=>X.context.frag.start-G.context.frag.start),_=null,K=null,J=[];for(let X of Z){let G=X.context.frag.start,te=G+X.context.frag.duration;_===null?G<=E&&EK&&(K=te,J.push(X))}return d.verifiedStart=_,d.verifiedEnd=K,{start:_,end:K,rows:J}},nr=(E=void 0)=>{if(!j())return null;if(E===void 0&&(E=me()),E===null||!j())return;if(!l())return Q("cancelled","not-allowed");let k;try{k=p(d.own.context)}catch{}if(!Number.isFinite(k)||k<0)return Q("failed","invalid-recovery");d.requiredHeadroomMs=k;let z=St(E);if(!(z.end===null||(z.end-E)*1e3new Promise((k,z)=>{let Z=!1,_=J=>{Z||(Z=!0,E.removeEventListener("abort",K),J?k():z(null))},K=()=>_(!1);if(E.addEventListener("abort",K,{once:!0}),E.aborted)return K();try{Promise.resolve(u(Object.freeze({signal:E}))).then(()=>_(!0),()=>_(!1))}catch{_(!1)}}),W=async(E=void 0)=>{if(!j()||d.checking||!d.verified)return;let k=nr(E);if(!k)return;d.checking=!0;let z=d.owner,Z=d.terminal,_=f,K=new Map,J=[],X=!0,G=()=>{if(X){X=!1;for(let ue of J){let he=(O.get(ue)??0)-1;he>0?O.set(ue,he):O.delete(ue)}d.releasePins===G&&(d.releasePins=null)}};d.releasePins=G;let te=()=>[...K.values()].some(({key:ue,row:he,identity:de})=>S.get(ue)!==he||!ut(Ae(he.context),de)||he.data.byteLength!==he.permit.size)?(Q("failed","coverage-evicted"),!1):[...K.values()].some(({key:ue,row:he})=>!pe({key:ue,scope:he.scope,context:he.context}))?(Q("cancelled","context-changed"),!1):!0,xe=async({covered:ue})=>{for(let[ye,le]of S)ue.rows.includes(le)&&!K.has(le)&&(K.set(le,{key:ye,row:le,identity:Ae(le.context)}),J.push(le.permit.key),O.set(le.permit.key,(O.get(le.permit.key)??0)+1));let he=[{context:d.own.context,permit:d.permit},...ue.rows.filter(ye=>ye.context!==d.own.context)],de=await Promise.all(he.map(ye=>t(ye.context,d.controller.signal)));return()=>{if(!j()||f!==_)return;if(de.some((ce,Pe)=>!ce||ce.key!==he[Pe].permit.key||ce.size!==he[Pe].permit.size||ce.sha256!==he[Pe].permit.sha256))return Q("failed","authority-changed");let ye=me();if(ye===null||!j())return;if(!l())return Q("cancelled","not-allowed");let le;try{le=p(d.own.context)}catch{}if(!Number.isFinite(le)||le<0)return Q("failed","invalid-recovery");if(d.requiredHeadroomMs=le,de.some((ce,Pe)=>typeof ce.current!="function"||ce.current(he[Pe].context)!==!0))return Q("failed","authority-changed");if(!j())return;if(performance.now()>=d.deadline)return Q("failed","deadline");if(!te())return;let be=St(ye,ue.rows);if(!(be.end===null||(be.end-ye)*1e3=d.deadline)return Q("failed","deadline");if(d.commitCompleted=!0,!te())return;let le=nr();if(!le||(ue=await xe(le),!ue()))return}let he=d.response,de=Z.context[Te];if(o?.(Z.context,he[0].data.byteLength,de?.peerBytes??0),!j())return;if(!l())return Q("cancelled","not-allowed");if((de?.commit??de?.accept)?.(Z.context),!j())return;de?.peerBytes>0&&(w.consumedPeerBytes+=de.peerBytes),d.state="ready",d.reason=null,d.released++,d.planningServiceMs=null,clearTimeout(d.timer),d.timer=null,clearTimeout(d.poll),d.poll=null,d.reserved=0;let ye=d.controller;if(d.owner=null,d.terminal=null,d.response=null,d.plan=[],d.cursor=null,d.frozenStart=null,!c){v=[];for(let le of[...U.values()])H(le)}try{z.deliver(Z,"onSuccess",he)}finally{try{ye.abort()}finally{de?.notify?.()}}}catch{j()&&Q("failed","authority-refused")}finally{G(),d.checking=!1,d.state==="buffering"&&(queueMicrotask(q),d.recheck&&(d.recheck=!1,queueMicrotask(W)))}},ve=(E,k,z,Z)=>{if(!d.enabled)return!0;if(d.state==="failed"||d.state==="cancelled")return d.state==="cancelled"&&(E.stats.aborted=!0),E.deliver(k,d.state==="cancelled"?"onAbort":"onError",d.state==="cancelled"?[E.stats,k.context,null]:[V(d.reason),k.context,null,E.stats]),!1;if(!z)return d.state==="idle"&&k.context.frag?.type==="main"&&k.context.frag.sn!=="initSegment"?(d.state="failed",d.reason="unsupported-context",d.failures++,E.deliver(k,"onError",[V(d.reason),k.context,null,E.stats]),!1):!0;if(d.state==="buffering")return Q("cancelled","superseded"),E.deliver(k,"onAbort",[E.stats,k.context,null]),!1;if(d.state!=="idle")return!0;let _=performance.now(),K=Z?.loadPolicy?.maxLoadTimeMs??Z?.timeout;if(Object.assign(d,{state:"buffering",owner:E,terminal:k,own:z,revision:f,reserved:We,entryAt:_,identity:{key:z.key,scope:z.scope,context:{frag:{start:z.context.frag.start,duration:z.context.frag.duration}}},contextUrl:k.context.url,fragUrl:k.context.frag.url,controller:new AbortController,deadline:_+Math.min(rr,Number.isFinite(K)&&K>0?K:rr)}),d.plan=(B?.upcoming??[]).map(J=>ge(J,z)),B?.owner===k.id&&(B.rolling=d.plan),d.cursor=null,k.context[Te]={peerBytes:0,genuine:()=>j()?{at:_,context:k.context}:null},!dt(z)||!l())return Q("failed","not-allowed"),!1;if(E.config.progressive===!0)return Q("failed","progressive-unsupported"),!1;if(me()===null||!j())return!1;try{if(!s(A()))return Q("failed","reservation-refused"),!1}catch{return Q("failed","reservation-refused"),!1}return j()?l()?(d.timer=setTimeout(()=>Q("failed","deadline"),Math.max(0,d.deadline-performance.now())),ft(),Promise.resolve().then(()=>j()?t(z.context,d.controller.signal):null).then(J=>{if(j()){if(!J||!Number.isSafeInteger(J.size)||J.size<1||J.size>We)return Q("failed","first-authority-refused");if(d.permit=J,d.reserved=J.size,!s(A()))return Q("failed","reservation-refused");w.highWaterBytes=Math.max(w.highWaterBytes,w.cacheBytes+A()),ie(),queueMicrotask(q)}}).catch(()=>{j()&&Q("failed","first-authority-refused")}),!0):(Q("cancelled","not-allowed"),!1):!1},ie=async()=>{if(!(!j()||!d.response||!d.permit||d.verifying||d.verified)){d.verifying=!0;try{let E=d.response[0].data,k=d.permit;if(!(E instanceof ArrayBuffer)||E.byteLength!==k.size||!await r(k,E,d.own.context,d.controller.signal))return j()&&Q("failed","first-integrity");if(!j())return;d.verified=!0,w.verified++,w.verifiedBytes+=E.byteLength,w.verifiedPeerBytes+=d.terminal.context[Te]?.peerBytes??0,W()}catch{j()&&Q("failed","first-integrity")}finally{d.verifying=!1}}};return{Loader:class{static relayswarmShadow=!0;constructor(k){this.config=k,this.inner=new n(k),this.stats=this.inner.stats,this.context=null,this.token=0}load(k,z,Z){this.abort(),this.context=k;let _={id:++$,context:k,callbacks:{...Z},settled:!1};this.pendingTerminal=_,Z={...Z};for(let xe of["onSuccess","onError","onTimeout","onAbort"])Z[xe]=(...ue)=>this.complete(_,xe,ue);let K=++this.token,J=ee(k,this.config,z,_.id),X=J&&S.get(J.key);if(!ve(this,_,J,z))return;let G=!X&&J&&U.get(J.key),te=X??G?.promise;if(te){G&&(w.coalesced++,G.waiters.add(this),this.warmPending=G,G.noteDemand(),m===G&&C.size===0&&(m=null,C.add(G),G.promote(),w.promotions++)),this.reuseAbort=new AbortController;let xe=f,ue=null,he,de=null,ye=()=>K===this.token,le=()=>{if(clearTimeout(he),F.delete(be),de!==null){let ce=O.get(de)-1;ce>0?O.set(de,ce):O.delete(de),de=null}},be=(ce=!1)=>{if(ce&&(le(),this.reuseAbort.abort()),!ye()||ue||this.originStarted)return;this.originStarted=!0,clearTimeout(he);let Pe={...Z,onProgress:(...Ce)=>{!ye()||ue==="cache"||(Ce[2]?.byteLength>0&&(ue="origin",this.reuseAbort.abort(),le()),Z.onProgress?.(...Ce))}};for(let Ce of["onSuccess","onError","onTimeout","onAbort"])Pe[Ce]=(...Ht)=>{!ye()||ue==="cache"||(ue="origin",this.reuseAbort.abort(),le(),Z[Ce]?.(...Ht))};this.start(k,z,Pe,K)};this.cancelReuse=()=>{le(),this.reuseAbort.abort()},F.add(be),Promise.resolve(te).then(async ce=>{if(!ye())return;if(this.releasePending(),g||!ce||xe!==f)return be(!0);if(ce.failure){let{name:Gn,args:Wr,stats:Yn}=ce.failure;ue="origin",le(),this.reuseAbort.abort(),Yn&&Object.assign(this.stats,Yn),Gn==="onError"?Z.onError(Wr[0],k,Wr[2],this.stats):Z[Gn](this.stats,k,Wr[2]);return}de=ce.permit.key,O.set(de,(O.get(de)??0)+1);let Pe=Math.max(0,Math.min(25,a(k)||0));Pe>0?he=setTimeout(be,Pe):be();let Ce;try{Ce=await t(k,this.reuseAbort.signal)}catch{}if(!ye()||ue==="origin")return;if(g||xe!==f)return be(!0);if(!Ce||Ce.key!==ce.permit.key||Ce.size!==ce.permit.size||Ce.sha256!==ce.permit.sha256)return N(J.key),be();ue="cache",le(),this.originStarted&&this.inner.abort(),Object.assign(this.stats,ce.stats);let Ht=ce.data.slice(0);w.localReuseBytes+=Ht.byteLength,ce.accepted||(ce.accepted=!0,ce.accept?.(k),w.consumedPeerBytes+=ce.peerBytes),o?.(k,Ht.byteLength,ce.peerBytes),Z.onSuccess({...ce.response,data:Ht},this.stats,k,ce.details),queueMicrotask(q)})}else this.start(k,z,Z,K);queueMicrotask(q)}start(k,z,Z,_){L.add(this),L.size+C.size>1&&m&&H(m);let K=this.pendingTerminal,J=()=>{L.delete(this),queueMicrotask(q)},X={...Z};X.onProgress=(...G)=>{if(!(g||_!==this.token||!K||K.settled||this.pendingTerminal!==K)){if(d.owner===this&&(G[0]?.loaded>(d.permit?.size??We)||G[2]?.byteLength>(d.permit?.size??We)))return Q("failed","first-oversize");if(d.owner===this&&G[2]!==null&&G[2]!==void 0){j();return}Z.onProgress?.(...G)}};for(let G of["onSuccess","onError","onTimeout","onAbort"])X[G]=(...te)=>{J(),_===this.token&&Z[G]?.(...te)};this.inner.load(k,z,X)}releasePending(){let k=this.warmPending;this.warmPending=null,k&&(k.waiters.delete(this),k.waiters.size||k.context[Te]?.onGenuine?.(),C.has(k)&&!k.waiters.size&&H(k))}complete(k,z,Z){if(!(!k||k.settled||this.pendingTerminal!==k)){if(d.owner===this&&d.terminal===k&&d.state==="buffering"){if(z==="onSuccess"){let _=Z[0]?.data;if(!(_ instanceof ArrayBuffer)||_.byteLength>(d.permit?.size??We))return Q("failed","first-oversize");d.response=Z,ie();return}d.state=z==="onAbort"?"cancelled":"failed",d.reason=z==="onAbort"?"origin-abort":"origin-error",z==="onAbort"?d.cancellations++:d.failures++,clearTimeout(d.timer),clearTimeout(d.poll),d.poll=null,d.controller?.abort(),d.releasePins?.(),d.owner=null,d.terminal=null,d.response=null,d.reserved=0,v=[],d.plan=[],d.cursor=null,d.frozenStart=null,d.planningServiceMs=null;for(let _ of[...U.values()])H(_);for(let _ of S.keys())N(_)}this.deliver(k,z,Z)}}deliver(k,z,Z){!k||k.settled||this.pendingTerminal!==k||(z!=="onSuccess"&&B?.owner===k.id&&(B=null),k.settled=!0,this.pendingTerminal=null,k.callbacks[z]?.(...Z))}cancel(k){let z=this.pendingTerminal;d.owner===this&&d.terminal===z&&Q("cancelled","caller-abort",!k&&!g),z&&B?.owner===z.id&&(B=null),this.token++,this.originStarted=!1,this.cancelReuse?.(),this.releasePending(),L.delete(this),z&&(this.stats.aborted=!0),k&&z&&(z.settled=!0,this.pendingTerminal=null);try{k?this.inner.destroy():this.inner.abort()}finally{k||this.complete(z,"onAbort",[this.stats,z?.context,null])}}abort(){this.cancel(!1)}destroy(){this.cancel(!0)}getCacheAge(){return this.inner.getCacheAge?.()??null}getResponseHeader(k){return this.inner.getResponseHeader?.(k)??null}},clear:D,startupSnapshot:()=>({enabled:d.enabled,state:d.state,reason:d.reason,heldObjects:d.state==="buffering"?x():0,heldBytes:d.state==="buffering"?w.cacheBytes+A():0,targetTime:d.targetTime,verifiedStart:d.verifiedStart,verifiedEnd:d.verifiedEnd,requiredHeadroomMs:d.requiredHeadroomMs,planningServiceMs:d.planningServiceMs,released:d.released,failures:d.failures,cancellations:d.cancellations,commitStarted:d.commitStarted,commitCompleted:d.commitCompleted,limits:{objects:Fn,bytes:We,deadlineMs:rr}}),contains(E){if(g||!l()||!Number.isFinite(E))return!1;for(let z of[...U.values(),...S.values()])if(z.scope===y&&jn(z,E))return!0;let k=B;if(!k||k.own.scope!==y||!jn(k.own,E))return!1;try{let z=k.rolling??e(k.own.context).map(Ae).filter(Boolean).filter(_=>_.scope===y).slice(0,2),Z=new Map([k.own,...z].map(_=>[_.key,_]));return(k.rolling?z.some(_=>!ne(_)):z.length!==k.upcoming.length||z.some((_,K)=>!ut(_,k.upcoming[K])))||[...U,...S].some(([_,K])=>!ut({...K,key:_},Z.get(_)))?(B=null,!1):!0}catch{B=null}return!1},pinned:E=>O.has(E),release(E){for(let[k,z]of S)z.permit.key===E&&N(k)},stop(){g=!0,D()},snapshot:()=>({...w,reservationBytes:A(),active:+!!m,promoted:C.size,trackedObjects:x(),queued:v.length,cacheObjects:S.size,limits:{objects:R(),bytes:We,speculativeWholeRequests:1,deadlineMs:rr,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},h=!1,u=null,p=v=>{if(!v.waiting)return;let b=Math.max(0,n()-v.queuedAt);c.waited++,c.waitTotalMs+=b,c.waitMaxMs=Math.max(c.waitMaxMs,b)},g=(v,b)=>{a.get(v.link)===v&&(a.delete(v.link),p(v),c[b]++,i(b),v.resolve(null))},f=(v,b=!1)=>{l.delete(v)&&(v.active=!1,b||t(v.charge),queueMicrotask(m))},m=()=>{if(clearTimeout(u),u=null,!h)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 b=v.deadline-n();u=setTimeout(m,Math.max(1,Math.ceil(Math.min(b,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)}},y=v=>{for(let b of[...a.values()])(!v||b.link===v)&&g(b,"cancelled");for(let b of[...l])(!v||b.link===v)&&(c.cancelled++,b.controller.abort(),f(b));m()};return{acquire(v,b){return h||a.has(v)||[...l].some(T=>T.link===v)||a.size>=o||!b.range&&(a.size||r(b.charge)>0)?(c.refused++,i("refused"),Promise.resolve(null)):new Promise(T=>{let B=n();a.set(v,{link:v,key:b.key,size:b.size,charge:b.charge,range:b.range?{start:b.range.start,end:b.range.end}:null,queuedAt:B,deadline:B+250,resolve:T,waiting:a.size>0,active:!1}),m()})},finish:f,cancel:y,recheck:m,stop(){h=!0,y(),clearTimeout(u),u=null},snapshot:()=>({enabled:!0,...c,queued:a.size,reservedBytes:[...l].reduce((v,b)=>v+b.charge,0),limits:{waitMs:250,waiters:o,perLink:1}})}}var nl=2,zr="webrtc",Wi=16,Wn=3e4,sl=1e4,Ki=300,Kn=32*1024,Vi=Object.freeze({mode:"shadow",originFallbackMs:1500,maxPeerWaitMs:5e3,originReserveMs:2e3,sustainablePeerWait:!1,warmAhead:!1,startupBufferTarget:null,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}),il=32768,ol=500,al=2e3,I=()=>performance.now(),qr=n=>{let e=n?.loading?.first;return Date.now()-(Number.isFinite(e)&&e>0&&e<=I()?I()-e:0)},eo=n=>Array.from(new Uint8Array(n),e=>e.toString(16).padStart(2,"0")).join(""),$i=new TextEncoder;async function Nt(n){return eo(await globalThis.crypto.subtle.digest("SHA-256",n))}function Gi(n){return new URL(n,globalThis.location?.href).pathname}function ll(n){try{return new URL(n,globalThis.location?.href).origin}catch{return String(n)}}function _e(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 cl(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 Vn(n){return{p50:_e(n,.5),p90:_e(n,.9)}}function Ke(n,e){n.push(e),n.length>ol&&n.shift()}function Pt(){let n=globalThis.navigator?.connection;return!!(n&&(n.type==="cellular"||n.saveData))}var Fr=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"]}),Ve=n=>Math.min(Number.MAX_SAFE_INTEGER,n+1),Yi=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"]),Zi=Object.freeze(["payload","none","timeout","abort","abandoned","closed","busy","send-error"]),hl=15e3,ul=250,dl=50,Xi=Object.freeze(["presence","dialStart","offerBeforeSend","offerIncoming","answerIncoming","glareBeforeRollback","glareAfterRollback","answerBeforeSend","upload","refresh","other"]),fl=Object.freeze(["admission","not-held","not-serving","banned","session-allowance","peer-limit","rate-limit","reservation-refused","reservation-inactive"]);function Ji(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 pl(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 gl(){return eo(globalThis.crypto.getRandomValues(new Uint8Array(12)))}function Qi(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 bl(n={}){let e=new $n(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 $n=class{constructor(e){this.options={...Vi,...e},this.options.iceTransportPolicy===void 0&&(this.options.iceTransportPolicy=Vi.iceTransportPolicy),this.startedAt=Date.now(),this.transportStartedAt=I(),this.transportSequence=0,this.transportRecords=[],this.transportDropped=0,this.transportCounters=Object.fromEntries(Object.entries(Fr).map(([t,r])=>[t,Object.fromEntries(r.map(s=>[s,0]))])),this.transportConnections=new WeakMap,this.peerEligibilityRecords=[],this.peerEligibilityDropped=0,this.peerEligibilityCounters=Object.fromEntries(Yi.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(Zi.map(t=>[t,0])),this.uploadRefusalCounters=Object.fromEntries(fl.map(t=>[t,0])),this.admissionCallCounters=Object.fromEntries(Xi.map(t=>[t,0])),this.disabledReason=this.#n(),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 Lt,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={}}#n(){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"&&!Nr(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>il)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(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&&!we(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.#Je(t),this.options.warmAhead||this.options.startupBufferTarget){this.warmAhead=Fi({Loader:e.config.fLoader,steady:this.options.warmAhead,startupTarget:this.options.startupBufferTarget,startupCommit:this.options.startupBufferCommit,startupRecovery:i=>Math.max(this.options.originReserveMs,(_e(this.#W(i),.9)||0)*1.25+100),allowed:()=>this.#p()&&e.media?.paused!==!0&&!Pt(),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 at(u=>this.options.getCommitment(i,{signal:u}),o,1e3);if(o.aborted||this.stopped)return null;let c=u=>!this.stopped&&this.#ce(l,{streamEvent:this.options.streamEvent,swarmId:this.options.swarmId,key:a,context:u,maxSegmentBytes:this.options.maxSegmentBytes,delegation:this.options.delegation,revokedDelegationIds:this.options.revokedDelegationIds,delegationRevocations:this.options.delegationRevocations}),h=c(i);return h&&h.size<=this.options.maxHeldBytes?{...h,key:a,current:u=>{let p=c(u);return!!(p&&p.size===h.size&&p.sha256===h.sha256)}}:null},verify:async(i,o,a,l)=>o instanceof ArrayBuffer&&o.byteLength===i.size&&!l.aborted&&await Nt(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,(_e(this.#W(i),.9)||0)*1.25+100);for(let c=0;ca)return Math.min(25,Math.max(0,(h-a)*1e3-l))}}catch{}return 0},onVerified:(i,o)=>(this.#rt(i.key),this.#T(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(al,r);this.coreRelease=r,this.coreWait=s.then(()=>{clearTimeout(i),this.timers.delete(i),this.coreWait=null,this.coreRelease=null}),this.#r("core",()=>this.#it().finally(r))}this.#r("start",()=>this.#lt()),typeof this.options.onMetrics=="function"&&this.#k(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,h]of l)h?Object.defineProperty(o,c,h):delete o[c]}},e.trigger=this.withheldTrigger)}updateTicket(e){return this.stopped||this.disabledReason||!this.#G()||!we(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.#F(),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.#se(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=Ve(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,h=g=>{let f=g;try{f??=r()}catch{}let m=y=>{try{let v=f?.[y];return Number.isSafeInteger(v)&&v>=0?v:null}catch{return null}};return{loaderLoadedBytes:m("loaded"),loaderTotalBytes:m("total")}},u=(g,f)=>this.#e({k:g,load:e,leg:t,at:this.#s(),ms:Math.round(I()-s),ranged:!1,...f});return u("originStart",{}),{progress:(g,f,m)=>{if(m){c||(c=!0,u("originCallback",{phase:"progress",outcome:null,stale:!0}));return}a||f!==!0||(a=!0,u("originProgress",{stale:!1,...h(g)}))},abortRequest:g=>{o||l||(l=!0,u("originAbortRequest",{reason:g,...h()}))},terminal:(g,f=null,m,y=!1)=>p(g,f,m,y)};function p(g,f,m,y){if(o){c||(c=!0,u("originCallback",{phase:"terminal",outcome:g,stale:!0}));return}o=!0;let v=y?{loaderLoadedBytes:null,loaderTotalBytes:null}:h(m);u("origin",{at:Math.floor(s)-i,outcome:g,bytes:Number.isSafeInteger(f)&&f>=0?f:null,stale:y,...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:nl,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:_e(this.signallingSamples,.5),p90Ms:_e(this.signallingSamples,.9),clock:{...this.session?this.session.clockDiagnostics():{aheadRejected:null,staleRejected:null,maxAheadSeconds:null,signalSamples:null,signalAgeMedianSeconds:null},origin:Xn(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:_e(this.peerLatencySamples,.5),peerLatencyP90Ms:_e(this.peerLatencySamples,.9),originLatencyMedianMs:_e(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.#L(),...this.multiHolder,originRangeOutcomes:{...this.originRangeOutcomes},timings:{durationMs:Vn(this.multiHolderTimings.map(o=>o[0])),slowestRequestMs:Vn(this.multiHolderTimings.map(o=>o[1])),requests:Vn(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)}#r(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.#r("timer",t)},Math.max(0,e));return this.timers.add(r),r}#k(e,t,r){let s=()=>{let i=e*t*(Math.random()*2-1);this.#h(e+i,()=>{try{r()}finally{s()}})};s()}#M(e,t){try{let r=Zn(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.#ze(s,a);if(t.#Y(s),t.options.peerSupplyHint&&t.#r("player-hint",()=>t.#B(s,l)),t.stopped||!s.frag||s.frag.sn==="initSegment"||s.part&&!t.options.swarmParts||!t.options.serveOnCellular&&Pt())return this.inner.load(s,i,o);if(l===0&&t.options.zeroBudgetPeerRace&&!this.hlsConfig.progressive&&t.#L()&&t.#l()){let S=new Map([...t.links.values()].filter(L=>t.#K(L,s)&&L.supportsRanges&&(t.remoteFraming.get(L.pubkey)??1)>=2&&!t.banned.has(L.pubkey)&&(L.have.size||t.options.lateHaveRace)).map(L=>[L,new Set(L.have)]));if(S.size)return this.loadCachedRace(s,i,o,a,S)}let c=i?.loadPolicy?.maxLoadTimeMs??i?.timeout;if(l===0&&t.options.latePeerRace&&!this.hlsConfig.progressive&&Ae(s)&&Number.isFinite(c)&&c>0&&t.#l())return this.loadLatePeerRace(s,i,o,a,c);let h=new AbortController,u={};this.active=u;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",y)};this.cancel=()=>{let S=this.active===u;return this.active=null,m(),h.abort(),S};let y=()=>{if(this.active!==u)return;this.active=null,this.pendingCallbacks=null,m(),h.abort(),t.counters.originFallbacks+=1,this.inner.stats.loading.start=0;let S=I(),L=!1,U=null,C=t.#C(s);C.then(w=>{!L&&!t.stopped&&(U=w,this.releaseFetch=t.#Z(w))}).catch(()=>{});let F=()=>L?!1:(L=!0,this.releaseFetch?.(),this.releaseFetch=null,!0),O=this.cancel;this.cancel=()=>(F(),O());let d=this.originTrace=t.#c(f,"fallback",()=>this.inner.stats);this.inner.load(s,i,{...o,onError:(...w)=>{d?.terminal("error",null,void 0,d!==this.originTrace),F(),o.onError?.(...w)},onTimeout:(...w)=>{d?.terminal("timeout",null,w[0],d!==this.originTrace),F(),o.onTimeout?.(...w)},onAbort:(...w)=>{d?.terminal("abort",null,w[0],d!==this.originTrace),F(),o.onAbort?.(...w)},onSuccess:(w,A,x,R)=>{if(L)return;let P=qr(A),{copy:N,size:M}=t.#S(w,s);if(!L&&(U&&N&&t.#T(U,new Uint8Array(N)),!!F())){if(this.pendingCallbacks=null,d?.terminal("payload",M||null,A,d!==this.originTrace),Ke(t.originLatencySamples,I()-S),t.#X(t.renditionOriginSamples,s,I()-S),t.options.peerSupplyHint&&M){let H=t.#v(s);!t.hintSizes.has(H)&&t.hintSizes.size>=16&&t.hintSizes.delete(t.hintSizes.keys().next().value),t.hintSizes.set(H,M);let D=I()-S;D>0&&Ke(t.hintOriginRates,M/D)}o.onSuccess(w,A,x,R),t.#M(R,P),M&&!t.stopped&&t.#r("peer-first-origin",async()=>{if(t.counters.originLoaded+=1,t.counters.bytesFromOrigin+=M,!U){let H=await C;N&&!t.stopped&&t.#T(H,new Uint8Array(N))}})}}})};if(l===0)return f=t.#i(s,0,0,a),t.#E(s,l,"no-budget",null,a),y();let v=()=>{$.onDeadline?.()||($.expired=!0,y())};g=setTimeout(v,l),t.lifecycle.signal.addEventListener("abort",y,{once:!0});let b=Math.max(t.options.originFallbackMs,t.options.maxPeerWaitMs),T=Math.max(l,Math.min(b,a.uncappedMs??l,a.sustainableMs??1/0));f=t.#i(s,l,T,a);let B={Loader:e,config:this.hlsConfig,loaderConfig:i},$={deadline:p+l,limit:p+T,originReserveMs:a.originReserveMs??t.options.originReserveMs,expired:!1,onDeadline:null,origin:B,extend:S=>{let L=Math.min($.limit,S);return this.active!==u||L<=$.deadline?!1:($.deadline=L,clearTimeout(g),g=setTimeout(v,Math.max(0,L-I())),!0)}};t.#ae(s,h.signal,$,l,a).then(S=>{if(!(this.active!==u||h.signal.aborted||t.stopped)){if(S&&!S.multi&&I()>=$.deadline&&t.#N(S.demand),!S||I()>=$.deadline&&!S.multi)return y();this.active=null,this.pendingCallbacks=null,m(),t.#O(this,S,s,o,p)}}).catch(S=>{this.active===u&&(t.#o("peer-first",S),y())})}loadCachedRace(s,i,o,a,l){let c=t.#i(s,0,t.options.maxPeerWaitMs,a),h={},u=new AbortController,p=I(),g=!0,f=!1,m=null,y,v;this.active=h,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 b=()=>{clearTimeout(v),t.lifecycle.signal.removeEventListener("abort",b),t.cachedRaces.delete(u),u.abort()};t.cachedRaces.add(u),t.lifecycle.signal.addEventListener("abort",b,{once:!0}),this.cancel=()=>{let S=g&&this.active===h;g=!1,this.active=null,b();try{this.inner.abort()}catch{}return S};let T=()=>!g||this.active!==h?!1:(g=!1,this.active=null,this.pendingCallbacks=null,b(),this.releaseFetch?.(),this.releaseFetch=null,!0);v=setTimeout(b,t.options.maxPeerWaitMs),t.counters.originFallbacks+=1,t.#E(s,0,"no-budget",null,a);let B=this.originTrace=t.#c(c,"cached",()=>this.inner.stats);try{this.inner.load(s,i,{...o,onProgress:(...S)=>{if(!g||this.active!==h){B?.progress(void 0,null,!0);return}let L=S[2]?.byteLength>0;L&&(f=!0,b()),B?.progress(S[0],L,!1),o.onProgress?.(...S)},onError:(...S)=>{B?.terminal("error",null,void 0,!g||this.active!==h),T()&&o.onError?.(...S)},onTimeout:(...S)=>{B?.terminal("timeout",null,S[0],!g||this.active!==h),T()&&o.onTimeout?.(...S)},onAbort:(...S)=>{B?.terminal("abort",null,S[0],!g||this.active!==h),T()&&o.onAbort?.(...S)},onSuccess:(S,L,U,C)=>{if((!g||this.active!==h)&&B?.terminal("payload",null,void 0,!0),!g||this.active!==h)return;let F=qr(L),{copy:O,size:d}=t.#S(S,s);!g||this.active!==h||(m&&O&&t.#T(m,new Uint8Array(O)),T()&&(B?.terminal("payload",d||null,L),Ke(t.originLatencySamples,I()-p),t.#X(t.renditionOriginSamples,s,I()-p),o.onSuccess(S,L,U,C),t.#M(C,F),d&&!t.stopped&&t.#r("cached-race-origin",async()=>{if(t.counters.originLoaded+=1,t.counters.bytesFromOrigin+=d,!m){let w=await(y??t.#C(s));O&&!t.stopped&&t.#T(w,new Uint8Array(O))}})))}})}catch(S){throw T(),S}if(!g)return;y=t.#C(s),y.then(S=>{g&&!t.stopped&&(m=S,this.releaseFetch=t.#Z(S))}).catch(()=>{});let $={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,u.signal,$,0,a).then(S=>{if(!(!S||!g||f||this.active!==h||u.signal.aborted||t.stopped||I()>=$.limit)){g=!1,this.active=null,this.pendingCallbacks=null,b(),this.releaseFetch?.(),this.releaseFetch=null,B?.abortRequest("peer-won");try{this.inner.abort()}catch{}t.counters.zeroBudgetPeerRaceWins+=1,t.#O(this,S,s,o,p)}}).catch(S=>{g&&!u.signal.aborted&&!t.stopped&&t.#o("cached-race",S)}).finally(b)}loadLatePeerRace(s,i,o,a,l){let c=t.#i(s,0,l,a),h={},u=new AbortController,p=I(),g=!0,f=!1,m=null,y;this.active=h,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===h&&!t.stopped,b=B=>!g||this.active!==h?!1:(g=!1,this.active=null,this.pendingCallbacks=null,y?.close(B),this.releaseFetch?.(),this.releaseFetch=null,!0);this.cancel=()=>{let B=g&&this.active===h;g=!1,this.active=null,y?.close("caller-abort"),this.releaseFetch?.(),this.releaseFetch=null;try{this.inner.abort()}catch{}return B};let T;y=t.#w({context:s,controller:u,entryAt:p,parentDeadline:p+l,current:v,arm:(B,$)=>(t.options.traceRequests&&t.traceLoads.set(B,c),t.#ae(B,u.signal,$,0,a).then(S=>{if(!S||!v()||u.signal.aborted||I()>=$.limit||!y.valid()||typeof $.revalidateAuthority!="function"||!$.revalidateAuthority())return!1;g=!1,this.active=null,this.pendingCallbacks=null,y.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,S,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:(...B)=>{if(!g||this.active!==h){T?.progress(void 0,null,!0);return}let $=B[2]?.byteLength>0;$&&(f=!0,y?.close("origin-progress")),T?.progress(B[0],$,!1),o.onProgress?.(...B)},onError:(...B)=>{T?.terminal("error",null,void 0,!g||this.active!==h),b("origin-error")&&o.onError?.(...B)},onTimeout:(...B)=>{T?.terminal("timeout",null,B[0],!g||this.active!==h),b("origin-timeout")&&o.onTimeout?.(...B)},onAbort:(...B)=>{T?.terminal("abort",null,B[0],!g||this.active!==h),b("origin-abort")&&o.onAbort?.(...B)},onSuccess:(B,$,S,L)=>{if((!g||this.active!==h)&&T?.terminal("payload",null,void 0,!0),!g||this.active!==h)return;let U=qr($),{copy:C,size:F}=t.#S(B,s);!g||this.active!==h||(m&&C&&t.#T(m,new Uint8Array(C)),b("origin-success")&&(T?.terminal("payload",F||null,$),Ke(t.originLatencySamples,I()-p),t.#X(t.renditionOriginSamples,s,I()-p),o.onSuccess(B,$,S,L),t.#M(L,U),F&&!t.stopped&&t.#r("late-race-origin",async()=>{if(t.counters.originLoaded++,t.counters.bytesFromOrigin+=F,!m){let O=await(y?.keyPromise??t.#C(s));C&&!t.stopped&&t.#T(O,new Uint8Array(C))}})))}})}catch(B){throw b("origin-throw"),B}g&&y?.keyPromise.then(B=>{g&&this.active===h&&!t.stopped&&(m=B,this.releaseFetch=t.#Z(B))}).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?.[Te]?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)}#A(){for(let e of[...this.latePeerOwners.values()])e.refresh()}#w(e){let t=Ae(e.context);if(!t||!this.#l())return null;let r=e.context[Te],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},h=(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),u=()=>{let p=c();return!p||!Number.isFinite(p.at)||Ae(p.context)?.key!==t.key?null:r?{...p.context,[Te]:r}:p.context};o.valid=()=>!o.closed&&e.current()&&!this.stopped&&o.generation===this.latePeerGeneration&&o.streamId===this.options.streamEvent?.id&&u()!==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=u();if(!g||i?.paused||i?.ended)return o.close("context-or-playback");if(o.windowEnd===null){let y=p.role==="startup-buffer-dependency";o.genuineAt=y?null:p.at,o.dependencyAt=y?s:null,o.dependencyDeadline=y?p.deadline:null,o.windowEnd=Math.min(e.parentDeadline,y?p.deadline:1/0,(y?s:p.at)+Math.min(4e3,this.options.lateWindowMs)),y&&p.signal.addEventListener("abort",()=>o.close("startup-buffer-ended"),{once:!0,signal:a.signal}),this.#f(o,"entered",y?"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.#L())return;let f=[...this.links.values()].filter(y=>h(y,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 y=await Promise.all(f.map(async S=>{if(!this.options.admit)return S;let L=this.admissionChecks.get(S.pubkey)?.ticket??this.admitted.get(S.pubkey)?.ticket,U=!1;try{U=await at(()=>this.#x(S.pubkey,L,"other"),o.controller.signal,Math.max(0,Math.min(this.options.admissionTimeoutMs,m-I())))===!0}catch{}return!U&&!o.closed&&S.close("admission"),U?S:null}));if(o.closed)return;let v=u();if(!e.current()||!v||I()>=m||o.generation!==this.latePeerGeneration)return o.close("inactive-after-admission");let b=y.filter(S=>S&&h(S,v));if(!b.length)return o.close("admission-or-have-refused","refused");o.validatedPeers=new Map(b.map(S=>[S,this.admitted.get(S.pubkey)?.ticket]));let T=Ae(v)?.context;if(!T||!o.valid())return o.close("context-after-admission");let B={deadline:m,limit:m,originReserveMs:0,expired:!1,onDeadline:null,knownKey:o.key,cachedOnly:new Map(b.map(S=>[S,new Set([o.key])])),lateHaveRace:!1,peerOnly:!0,extend:()=>!1,currentValid:o.valid,revalidateAuthority:!0};!await e.arm(T,B)&&!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.#F(),this.firstPeerSegmentAtMs===null&&(this.firstPeerSegmentAtMs=Date.now()-this.startedAt),Ke(this.peerLatencySamples,o-i),p.frag&&this.peerFragments.add(p.frag)}},h=()=>{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{}}},u=p=>{c(p),h()};r[Te]?Object.assign(r[Te],{peerBytes:l,accept:u,commit:c,notify:h}):u(r),!r[Te]&&this.#p()&&!this.held.has(t.key)&&this.#T(t.key,t.bytes.slice()),s.onSuccess({url:r.url,data:t.bytes.buffer,code:200},e.peerStats,r,null)}async#B(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(h=>h.sn===e.frag.sn&&h.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}`,h=a?await this.#C(a):null;if(this.stopped||r!==this.hintGeneration)return null;let u=a&&this.discovery.contexts.get(a.frag.type||"main"),p=h?[...this.links.values()].filter(T=>this.#P(T)&&T.have.has(h)&&T.supportsRanges===!0&&(this.remoteFraming.get(T.pubkey)??1)>=2&&!this.banned.has(T.pubkey)&&!(u?.rendition===c&&this.discovery.stale(u,T.pubkey))).map((T,B)=>{let $=this.peerSelection.summary(T).throughputBytesPerSecond;return[B+1,null,$?$/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),y=_e(this.renditionOriginSamples.get(c)||[],.5),v={rendition:c,size:m,peers:p,origin:[null,m&&y?m/y:_e(this.hintOriginRates,.5)],sharedFirstByteMs:this.peerSelection.firstByteMs(),sharedRate:this.peerSelection.rate(),availableMs:t,maxHolders:this.options.maxHoldersPerObject},b=this.core?.playerHint(v);return b&&this.options.traceRequests&&this.#e({k:"playerHint",at:this.#s(),input:v,out:b}),b?{...b,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=_t(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=Ae(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,h)=>(parseInt(c,16)^parseInt(e[h],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)}}}#ze(e,t){if(e?.[Te])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=_e(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,(_e(this.#W(e),.9)||0)*1.25+100),a,l,c,h=(a=e?.part?.start)??e?.frag?.start,u=Number.isFinite(h)&&h>r.currentTime?Math.min(l=r.buffered.end(i),h):l=r.buffered.end(i),p=Math.max(0,(u-(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(u),fragmentStart:f(h),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||Gi)(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 Nt($i.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}#Fe({key:e,rendition:t,context:r}){let s=l=>l.sort((c,h)=>c-h).slice(0,8),i=[],o=[],a=[];for(let l of this.links.values()){let c=this.#U(l.pubkey);this.#q(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(h=>this.#q(h,i));if(t&&![...this.links.values()].some(h=>h.have.has(s))){for(let h of a)this.discovery.holderMiss(o,h.pubkey,s);return}let l=a.filter(h=>e.asked.has(h.pubkey)||r.includes(h.pubkey)),c=[];for(let h of l)this.discovery.holderMiss(o,h.pubkey,s)&&(this.discovery.counters.heldMiss++,c.push(this.#U(h.pubkey)));c.length&&e.row?.heldMissHolders&&(e.row.heldMissHolders=c.sort((h,u)=>h-u).slice(0,8))}catch{}}}#je(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(!Yi.includes(r))return;let h=m=>Number.isSafeInteger(m)&&m>=0?m:null,u=null,p=null;try{u=h(e?.frag?.cc)}catch{}try{p=h(e?.frag?.level)}catch{}let g=I()-this.transportStartedAt,f={atMs:Number.isFinite(g)?Math.max(0,Math.round(g)):0,cc:u,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.#Fe(a))}catch{Object.assign(f,{holders:null,haveHolders:null,staleHolders:null,heldMissHolders:null})}a.row=f}this.peerEligibilityCounters[r]=Ve(this.peerEligibilityCounters[r]),this.peerEligibilityRecords.length===64&&(this.peerEligibilityRecords.shift(),this.peerEligibilityDropped=Ve(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)||[];Ke(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}}#We(e,t,r,s){if(!(t>0)||!Number.isFinite(t)||rWi&&o.firstBytes.shift();let l=s-r;l>=Ki&&i>=Kn&&(o.flows.push({value:Math.min(1e6,i/l),flowMs:l,at:a}),o.flows.length>Wi&&o.flows.shift())}#pe(e,t,r=null){if(!e||e.closed||!Number.isSafeInteger(t)||t<=0)return;let s=this.#oe(e);Number.isFinite(r)&&(s.flows=s.flows.filter(i=>i.at>=r)),s.usefulAt=I()}#Ve(e,t,r){let s=this.#oe(e),i=I();s.firstBytes=s.firstBytes.filter(u=>i-u.at<=Wn),s.flows=s.flows.filter(u=>i-u.at<=Wn);let o=s.firstBytes.reduce((u,p)=>u===null?p.value:(u+p.value)/2,null),a=s.flows.filter(u=>u.flowMs>=(o??0)*3),l=cl((a.length>=2?a:s.flows).map(u=>u.value),.75),c=l!==null&&(o??0)+r/l<=t,h=l===null&&(o??0)=sl)return{state:s,firstByteMs:null,rate:null,refresh:!0};if(l===null)return null}return{state:s,firstByteMs:o,rate:l,refresh:!1}}#$e(e,t){let r=_e(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>=hl?"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)}#J(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 O=w=>[...r.cachedOnly].filter(([A,x])=>(!w||x.has(c))&&A.have.has(c)&&this.links.get(A.pubkey)===A&&this.#K(A,e)&&!this.banned.has(A.pubkey)&&A.supportsRanges===!0&&(this.remoteFraming.get(A.pubkey)??1)>=2).map(([A])=>A),d=O(!0);if(!d.length&&r.lateHaveRace){for(d=O(!1);!d.length&&!t.aborted&&!this.stopped&&I()0}if(t.aborted||this.stopped||I()>=r.limit||(r.cachedHolders=new Set(d),!r.cachedHolders.size||!this.#L()))return null;this.counters.zeroBudgetPeerRaces+=1}let h=this.#v(e),u=l?.rendition===h&&this.discovery.contexts.get(l.mediaType)===l?l:null;if(u&&!r.cachedOnly){this.discovery.demand(l.mediaType,h,c);let O=this.discovery.counters.checks;this.#te();try{this.#je(u,O)}catch{}}let p={key:c,rendition:h,context:u,recorded:!1,asked:new Set,row:null},g=![...this.links.values()].some(O=>O.have.has(c));if(g&&!this.#I(c,h,e))return this.#E(e,s,"no-have-no-wait",!1,i,void 0,p,!1,o),null;let f=this.renditionSizes.get(h),m=g?this.#$e(c,h):0,y=f?this.peerSelection.projectMs(f):null,v=!g&&this.#L()&&[...this.links.values()].some(O=>this.#K(O,e)&&O.supportsRanges===!0&&O.have.has(c)&&!this.banned.has(O.pubkey)&&(this.remoteFraming.get(O.pubkey)??1)>=2&&!(u&&this.discovery.stale(u,O.pubkey))),b=r.cachedOnly||v?"unknown":this.#ge(y,m,r),T=null;if(b==="late"&&!g&&this.#be(p,r)&&(T=this.#J("entry",y,m,r),b="stretch"),b==="late")return this.#E(e,s,"projected-late",!g,i,this.#J("entry",y,m,r),p,!1,o),this.#N(p,{everyServing:!0}),this.counters.peerProjectedLate+=1,null;this.#me(b,m+y,r),g&&(this.#E(e,s,"no-have-wait",!1,i,void 0,p,!1,o),this.counters.coordinatedWaits+=1);let B=r.deadline-I();if(t.aborted||this.stopped||B<=0)return null;this.counters.commitmentRequests+=1;let $=at(O=>{if(t.aborted||this.stopped||I()>=r.deadline)throw new Error("Commitment load no longer active.");return this.options.getCommitment(e,{signal:O})},t,B).then(O=>({ok:!0,event:O}),()=>({ok:!1}));if(g){for(;!t.aborted&&!this.stopped&&I()d.have.has(c));){if(!this.#I(c,h,e))return this.#E(e,s,"wait-no-longer-eligible",!1,i,void 0,p,!1,o),null;await this.#Q(c,Math.min(100,r.deadline-I()),t)}let O=t.aborted||this.stopped;if(O||I()>=r.deadline)return this.#E(e,s,O?"wait-aborted":"wait-expired",null,i,void 0,p,!1,o),(!O||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 S,L;try{let O=await $;if(!O.ok)throw new Error("Commitment unavailable.");L=O.event,S=this.#ce(O.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(!S)return this.counters.commitmentRejected+=1,null;if(r.currentValid&&!r.currentValid()||(r.revalidateAuthority===!0&&(r.revalidateAuthority=()=>!!this.#ce(L,{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&&S.v!==3)return null;if(!this.renditionSizes.has(h)&&this.renditionSizes.size>=16&&this.renditionSizes.delete(this.renditionSizes.keys().next().value),this.renditionSizes.set(h,S.size),S.v===3&&this.options.multiHolder){let O=await this.#Ze(e,t,r,c,S,l,o);if(O!==void 0)return O&&g&&(this.counters.coordinatedPeerLoads+=1),O&&{...O,holderContext:u}}if(r.cachedOnly)return null;let U=this.peerSelection.projectMs(S.size),C=this.#ge(U,0,r);if(C==="late"&&!g&&(T!==null||this.#be(p,r))&&(T=this.#J("commitment",U,0,r),C="stretch",p.row&&(p.row.projection={...T},p.row.trial=!0)),C==="late")return this.#E(e,s,"projected-late",!0,i,this.#J("commitment",U,0,r),p,!1,o),this.counters.peerProjectedLate+=1,null;this.#me(C,U,r);let F=new Set;for(;!t.aborted&&!this.stopped&&I()O||(d??0)>O)return this.counters.peerSkippedLate+=1,null;let w=(V,re)=>this.peerSelection.estimate(V,S.size)===null||this.peerSelection.estimate(V,S.size)*1.25+25<=re,A=T&&F.size===0?this.#ye(c,p.context):null;A&&this.peerSelection.markSelected(A);let x=A??this.peerSelection.select([...this.links.values()].filter(V=>this.#P(V)),c,F,S.size,O);if(!x){if(![...this.links.values()].some(V=>!V.closed&&!F.has(V.pubkey)&&V.have.has(c)&&w(V,O)))return this.counters.peerNoFit+=1,this.#N(p,{unfit:[...this.links.values()].filter(V=>!V.closed&&!F.has(V.pubkey)&&V.have.has(c)&&!w(V,O)).map(V=>V.pubkey)}),null;await this.#Q(c,Math.min(100,r.deadline-I()),t);continue}F.add(x.pubkey),p.asked.add(x.pubkey),A&&(this.counters.peerUntestedTrial+=1);let R=this.peerSelection.estimate(x,S.size);R!==null&&r.extend(I()+R*1.25+25)&&(this.counters.peerWaitExtended+=1);let P=I(),N=r.deadline-I(),M=[...this.links.values()].filter(V=>this.#P(V)&&!F.has(V.pubkey)&&V.have.has(c)&&w(V,N)).length,H=N-Math.min(2,M)*25,D=R===null?Math.min(N,Math.max(25,H)):Math.min(N,Math.max(25,N/Math.min(3,M+1),R*1.25+25)),q=this.#Xe(t,P,S.size,r,d),ee;try{ee=await x.request(c,Math.max(1,D),{signal:q.signal,expectedSize:S.size,onProgress:q.progress,onResult:V=>this.#we(e,x,N,V,null,o)})}finally{q.done()}if(this.peerSelection.observe(q.observation()),q.abandoned)return this.#R(x,I()-P),this.counters.peerAbandoned+=1,this.#N(p),null;if(!ee||t.aborted||this.stopped){!t.aborted&&!this.stopped&&this.#R(x,I()-P);continue}let j=await Nt(ee);if(this.stopped)return null;if(ee.byteLength!==S.size||j!==S.sha256){if(this.#R(x,I()-P),this.counters.peerCorrupt+=1,this.banned.add(x.pubkey),p.asked.delete(x.pubkey),x.close("integrity"),t.aborted)return r.expired&&this.#N(p),null;continue}return t.aborted?(r.expired&&this.#N(p),null):S.expiresAt<=Math.floor(Date.now()/1e3)?null:(this.#R(x,I()-P,ee.byteLength),g&&(this.counters.coordinatedPeerLoads+=1),A&&(this.counters.peerUntestedTrialLoaded+=1),{key:c,bytes:ee,discoveryContext:l,holderContext:u,pubkey:x.pubkey,demand:p,connection:x.pc})}return!this.stopped&&(!t.aborted||r.expired)&&this.#N(p),null}#Ge(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?.[Te]&&!e.closed&&this.peerLeases.has(e))}#Ye(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#Ze(e,t,r,s,i,o,a){if(r.currentValid&&!r.currentValid())return null;let l=this.options.transferWorkerUrl!==void 0;if(l&&(!this.#L()||this.transferWorkerState!=="ready"))return null;if(!this.#L()||!Array.isArray(i.pieces))return;let c=ll(e.url);if(!r.peerOnly&&this.originsWithoutRanges.has(c))return l?null:void 0;let h=b=>this.links.get(b.pubkey)===b&&!b.closed&&b.supportsRanges===!0&&b.have.has(s)&&!this.banned.has(b.pubkey)&&(this.remoteFraming.get(b.pubkey)??1)>=2&&(!r.cachedHolders||r.cachedHolders.has(b)),u=[...this.links.values()].filter(b=>h(b)&&this.#K(b,e)),p=()=>u.filter(b=>h(b)&&this.#P(b)),g=p();if(!g.length&&e?.[Te]&&u.some(b=>this.peerLeases.has(b))&&(await this.#Ye(u,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(b=>[b,this.#Ve(b,Math.max(0,r.limit-I()),i.pieceSize)]).filter(([,b])=>b!==null));if(!f.size)return this.counters.peerNoFit+=1,null;let m=[...f.keys()],y={};for(let b of m)this.peerLeases.set(b,y);this.peerAdmission.claims+=m.length;let v=()=>{t.removeEventListener("abort",v);for(let b of m)this.peerLeases.get(b)===y&&this.peerLeases.delete(b);for(let b of[...this.peerLeaseWaiters])this.#h(0,b);this.latePeerOwners.size&&this.#h(0,()=>this.#A())};t.addEventListener("abort",v,{once:!0});try{let b=new Map(m.map(x=>[this.#Ge(x),x])),T=Math.floor(r.limit),B=r.peerOnly?r.limit:r.limit+r.originReserveMs,$={size:i.size,sha256:i.sha256,pieces:i.pieces,deadline:T,maxHolders:this.options.maxHoldersPerObject,originReserveMs:0,...r.peerOnly?{peerOnly:!0}:{}},S;try{S=l?await this.transferWorker.transfer($,{signal:t}):this.core.transfer($)}catch{return null}if(this.stopped||t.aborted||l&&I()>=T||r.currentValid&&!r.currentValid()||typeof r.revalidateAuthority=="function"&&!r.revalidateAuthority()||m.some(x=>!h(x)||x.busy||this.peerLeases.get(x)!==y))return S?.free(),null;if(!S)return l||r.peerOnly?null:void 0;this.multiHolder.transfers+=1;let L=a,U=this.traceBase,C=(x,R,P)=>{let N=Math.floor(I()),M=D=>(this.options.traceRequests&&this.#e({k:"xfer",load:L,op:x,at:N-U,...R,out:D&&{c:D.commands.map(({t:q,peer:ee,p:j})=>({t:q,...ee!==void 0?{peer:ee}:{},...j?{p:[...j]}:{}})),next:D.next===null?null:D.next-U,late:D.late,finished:D.finished}}),D),H=P(N);return H?.then?H.then(M):M(H)};r.extend(r.limit);let F=i.pieceSize,O=({start:x,end:R})=>[x*F,Math.min(R*F,i.size)],d=[...b].map(([x,R])=>[x,f.get(R).firstByteMs,f.get(R).rate]),w=r.peerOnly?null:_e(this.#W(e),.5),A=r.peerOnly?null:[0,w?i.size/w:null];return await new Promise(x=>{let R=new Map,P=new Set,N=new WeakSet,M=new Map,H=new Map,D=!1,q=null,ee=null,j=null,V=0,re=0,ae=(W,ve)=>{let ie=W?.verified==null?0:Math.max(0,W.verified-re);return W?.verified!=null&&(re=Math.max(re,W.verified)),this.multiHolder.unusedBytes+=ve-ie,ie},ge=I(),ne=0,pe=0,Q=W=>(W!==null&&(clearTimeout(W),this.timers.delete(W)),null),me=W=>{if(!D){D=!0,q=Q(q),ee=Q(ee);for(let ve of[...R.values(),...P])ve.abort();j?.(),r.onDeadline=null,t.removeEventListener("abort",et),S.free(),x(W)}},et=()=>me(null);t.addEventListener("abort",et,{once:!0});let Ie=(W,ve,ie,Be=ft)=>{if(D)return;let E=k=>{if(!D){if(r.currentValid&&!r.currentValid()||(l||r.peerOnly)&&I()>=B)return me(null);k?Be(k):me(null)}};try{let k=C(W,ve,ie);k?.then?k.then(E,()=>me(null)):E(k)}catch{me(null)}},jr=(W,ve)=>{if(W.t==="request"){let ie=b.get(W.peer),Be=new AbortController;R.set(W.peer,Be);let[E,k]=O(W.range),z=I(),Z=Math.max(1,T-z),_=null,K=-1/0;pe+=1,f.get(ie).refresh&&(f.get(ie).refreshStartedAt??=I(),f.get(ie).state.probeAt=I());let J=X=>{let G=I();D||R.get(W.peer)!==Be||G-KS.progress(te,W.peer,X)))};ie.request(s,Z,{signal:Be.signal,expectedSize:k-E,onProgress:J,range:{start:W.range.start,end:W.range.end,objectSize:i.size},onResult:X=>{_=X,this.#we(e,ie,Z,X,W.range,a)}}).then(X=>{R.get(W.peer)===Be&&R.delete(W.peer),ne=Math.max(ne,I()-z),!D&&(_?.firstByteMs!==null&&_?.elapsedMs!==null&&_?.receivedBytes&&this.peerSelection.observe({firstByteMs:_.firstByteMs,bytes:_.receivedBytes,flowMs:_.elapsedMs-_.firstByteMs}),X?(this.#R(ie,I()-z,X.byteLength),Ie("delivered",{source:W.peer,p:[W.range.start,W.range.end],bytes:X.byteLength},G=>S.delivered(G,W.peer,W.range,X),G=>{let te=ae(G,X.byteLength);this.multiHolder.peerBytes+=te,te>0&&M.set(ie.pc,(M.get(ie.pc)??0)+te);let xe=_?.elapsedMs-_?.firstByteMs;te>0&&f.get(ie).refresh&&_?.receivedBytes>=Kn&&Number.isFinite(xe)&&xe>=0&&xeS.failed(G,W.peer))))},()=>{D||Ie("failed",{source:W.peer},X=>S.failed(X,W.peer))})}else if(W.t==="origin"){if(r.peerOnly){this.multiHolder.failed+=1,me(null);return}j??=this.#Z(s);let ie=new AbortController,[Be,E]=O(W.range),k=I(),z=null,Z=K=>{z=K,this.originRangeOutcomes[K.outcome]=Ve(this.originRangeOutcomes[K.outcome])};P.add(ie),this.multiHolder.originRanges+=1;let _=()=>{this.originsWithoutRanges.has(c)||(this.originsWithoutRanges.add(c),this.multiHolder.originRangesIgnored+=1)};(r.origin?.Loader?Ui(r.origin,e,Be,E,{signal:ie.signal,onIgnored:_,onResult:Z}):zi(e,Be,E,{signal:ie.signal,onIgnored:_,onResult:Z})).then(K=>{if(P.delete(ie),this.options.traceRequests&&this.#e({k:"origin",load:L,at:this.#s(k),ms:Math.round(I()-k),ranged:!0,range:[W.range.start,W.range.end],outcome:z?.outcome??(K?"payload":D?"abort":"none"),httpStatus:z?.httpStatus??null,bytes:K?.byteLength??null}),D)return;let J=[W.range.start,W.range.end];if(!K)return Ie("failed",{source:"origin"},X=>S.failed(X,"origin"));this.#We(e,I()-k,K.byteLength,i.size),this.counters.bytesFromOrigin+=K.byteLength,Ie("delivered",{source:"origin",p:J,bytes:K.byteLength},X=>S.delivered(X,"origin",W.range,K),X=>{let G=ae(X,K.byteLength);this.multiHolder.originBytes+=G,V+=G,ft(X)})})}else if(W.t==="cancel"||W.t==="abandon"){let ie=R.get(W.peer);W.t==="abandon"&&(this.multiHolder.abandoned+=1,ie&&N.add(ie)),ie?.abort(W.t==="abandon"?ot.ABANDON_REASON:void 0)}else if(W.t==="ban"){let ie=b.get(W.peer);this.multiHolder.bans+=1,this.counters.peerCorrupt+=1,this.banned.add(ie.pubkey),ie.close("integrity")}else if(W.t==="deliver"){this.multiHolder.delivered+=1,this.multiHolderTimings.push([I()-ge,ne,pe]),this.multiHolderTimings.length>128&&this.multiHolderTimings.shift();let ie=ve.bytes.byteOffset===0&&ve.bytes.byteLength===ve.bytes.buffer.byteLength?ve.bytes:ve.bytes.slice();me(i.expiresAt<=Math.floor(Date.now()/1e3)?null:{key:s,bytes:ie,discoveryContext:o,multi:!0,peerBytes:Math.max(0,i.size-V),contributions:[...M].map(([Be,E])=>({connection:Be,bytes:E})),shortRefreshes:[...H].map(([Be,E])=>({connection:Be,at:E}))})}else W.t==="fail"&&(this.multiHolder.failed+=1,me(null))},ft=W=>{if(!D){if(!W)return me(null);for(let ve of W.commands)if(jr(ve,W),D)return;q=Q(q),W.next!==null&&(q=this.#h(Math.max(0,W.next-I()),()=>{q=null,Ie("tick",{},ve=>S.tick(ve))}))}};r.onDeadline=()=>D?!1:(Ie("tick",{},W=>S.tick(W)),!D&&ee===null&&(ee=this.#h(Math.max(0,r.limit+r.originReserveMs-I()),()=>{ee=null,me(null)})),!0);let St=[...f.values()].some(W=>W.refresh||W.firstByteMs===null)?null:this.peerSelection.firstByteMs(),nr=[...b].filter(([,W])=>f.get(W).rate===null).map(([W])=>W),sr={peers:d,origin:A,sharedFirstByteMs:St,sharedRate:this.peerSelection.rate(),probePeers:nr};Ie("start",this.options.traceRequests?{size:i.size,pieces:i.pieces.length,pieceSize:F,deadline:T-U,maxHolders:this.options.maxHoldersPerObject,originReserveMs:0,...r.peerOnly?{peerOnly:!0}:{},...structuredClone(sr),holders:[...b].map(([W,ve])=>[W,this.#U(ve.pubkey)])}:null,W=>S.start(W,sr),W=>{W?.late&&(this.multiHolder.late+=1),ft(W)})})}finally{v()}}#Xe(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(),h=null,u={abandoned:!1,signal:o.signal},p=()=>{u.abandoned||o.signal.aborted||(u.abandoned=!0,o.abort(ot.ABANDON_REASON))},g=null;if(i!==null){let m=c?s.deadline-r/c:-1/0;g=setTimeout(()=>{h===null&&p()},Math.max(ul,i*3,m-I()))}let f=m=>{let y=l.at(-1);if(!y)return null;let v=l[0];for(let b of l)if(b[0]<=y[0]-m)v=b;else break;return y[0]-v[0]>=150?{bytes:y[1]-v[1],ms:y[0]-v[0]}:null};return u.progress=(m,y,v)=>{let b=I();if(h===null&&(h=Number.isFinite(v)?v:b-t),l.push([b,m]),l.length>256&&l.shift(),b-ts.deadline)&&p()},u.observation=()=>{let m=l.length?l.at(-1)[0]-l[0][0]:0,y=f(Math.max(300,m/2));return{firstByteMs:h,bytes:y?.bytes??0,flowMs:y?.ms??0,totalFlowMs:m}},u.done=()=>{clearTimeout(g),e.removeEventListener("abort",a)},u}#R(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(!Zi.includes(s.outcome))return;this.#Ke(t,s);let a=p=>Number.isFinite(p)&&p>=0?p:null,l=p=>Number.isSafeInteger(p)&&p>=0?p:null,c=null,h=null;try{c=l(e?.frag?.cc)}catch{}try{h=l(e?.frag?.level)}catch{}let u={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:h,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:Fr["link-close"].includes(s.closeReason)?s.closeReason:null};this.peerRequestCounters[s.outcome]=Ve(this.peerRequestCounters[s.outcome]),this.peerRequestRecords.length===64&&(this.peerRequestRecords.shift(),this.peerRequestDropped=Ve(this.peerRequestDropped)),this.peerRequestRecords.push(u),this.#e({k:"request",load:o,at:this.#s(),range:i?[i.start,i.end]:null,...u})}catch{}}#Je(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.#Qe(i);if(this.race=l,!l)return this.inner.load(i,o,a);let c=[],h=0,u=l.sampled||t.#xe(),p={...a,onProgress:a.onProgress?(g,f,m,y)=>{try{m?.byteLength&&(u&&c.push(m.slice(0)),h+=m.byteLength)}catch{}a.onProgress(g,f,m,y)}:void 0,onSuccess:(g,f,m,y)=>{let v=qr(f),b=null,T=0;try{let B=g?.data;B?.byteLength?(u&&(b=B.slice(0)),T=B.byteLength):h&&(u&&(b=r.join(c)),T=h)}catch{b=null,T=0}l.originSucceeded=!0,a.onSuccess(g,f,m,y),t.#M(y,v),T?t.#r("origin-loaded",()=>t.#tt(l,b,T)):t.#r("origin-empty",()=>t.#z(l))},onError:(...g)=>{t.#r("origin-error",()=>t.#z(l)),a.onError(...g)},onTimeout:(...g)=>{t.#r("origin-timeout",()=>t.#z(l)),a.onTimeout(...g)}};return a.onAbort&&(p.onAbort=(...g)=>{t.#r("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,h)=>c+h.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}#Qe(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||Gi)(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.#et(o)),o}catch(t){return this.#o("begin-race",t),null}}async#et(e){if(e.keyPromise=Nt($i.encode(e.keyText)),e.key=await e.keyPromise,this.stopped)return;if(!e.sampled||!this.options.serveOnCellular&&Pt())return e.peerDone=!0,e.skipPeers=!0,this.#r("settle",()=>this.#ee(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.#r("settle",()=>this.#ee(e))}#Q(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#tt(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,Ke(this.originLatencySamples,i-e.t0),e.sampled&&(e.originDigest=await Nt(s)),e.originDone=!0,await e.keyPromise,!this.stopped&&(s&&this.#T(e.key,s),this.#r("settle",()=>this.#ee(e)))}#z(e){e.settled||e.originDone||(e.controller.abort(),e.originDone=!0,e.originFailed=!0,this.#r("settle",()=>this.#ee(e)))}async#ee(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 Nt(e.peerBytes)!==e.originDigest){this.#R(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.#R(e.peerLink,e.requestMs,e.peerBytes.byteLength),this.firstPeerSegmentAtMs===null&&(this.firstPeerSegmentAtMs=Date.now()-this.startedAt),Ke(this.peerLatencySamples,s),t.bytesFromPeers+=e.peerBytes.byteLength,s<=this.options.originFallbackMs?(t.peerInTime+=1,t.peerInTimeBytes+=e.peerBytes.byteLength):t.peerLate+=1}#T(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)}#rt(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||!Pt())}#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#nt(e,t,r=null){if(this.uploadPacer)return this.#st(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 h=xt(i.byteLength),u=r.start*h,p=Math.min(r.end*h,i.byteLength);if(!(ua)return this.#y("session-allowance"),null;let l=[...this.links.values()].filter(h=>h!==e&&(h.outboundInFlight>0||Date.now()-h.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:u}),this.lifecycle.signal,this.options.admissionTimeoutMs)===!0}catch{this.#o("upload-reservation")}if(!h||this.stopped||e.closed||this.options.serve!==!0||!this.options.serveOnCellular&&Pt())return h||(this.uploadQuotaBytes-=o),this.#y(h?"reservation-inactive":"reservation-refused"),null}if(this.counters.bytesUploaded+=o,this.counters.uploadsServed+=1,this.options.testHooks?.corruptUploads){let h=i.slice();return h[h.length>>1]^=255,h}return i}#y(e){this.counters.uploadsRefused+=1,this.uploadRefusalCounters[e]=Ve(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&&Pt()||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(!h())return null;let u=this.admissionChecks.get(e.pubkey)?.ticket??this.admitted.get(e.pubkey)?.ticket;if(this.options.admit&&!await at(()=>this.#x(e.pubkey,u,"upload"),c,this.options.admissionTimeoutMs))return this.#y("admission"),e.close("admission"),null;if(!h())return null;if(this.uploadQuotaBytes+=i.charge,o=!0,this.options.reserveUploadBytes){try{a=await at(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(!h()||this.options.admit&&this.admitted.get(e.pubkey)?.ticket!==u)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#it(){this.coreState="loading";try{let e=await Ni(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.#ot(e)}catch(e){this.coreState="failed",this.options.transferWorkerUrl!==void 0&&(this.transferWorkerState="failed",this.transferWorkerReason="core-failed"),this.#o("core",e)}}async#ot(e){this.transferWorkerState="loading";try{let t=this.options.WorkerImpl,r=await Hi({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.#L();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()}#L(){return this.options.multiHolder===!0&&this.options.mode==="peer-first"&&!!this.core&&!this.core.retired&&this.coreLinks.js===0}#at(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 ot(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,Mi(e,t)}async#lt(){let e=this.options.secretKey||Vt();if(this.pool=new _r(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 Or({pool:this.pool,swarmId:this.options.swarmId,secretKey:e,maxEventAgeSeconds:60}),this.session.onPresence(t=>this.#r("presence",()=>this.#gt(t))),this.session.onSignal(t=>this.#r("signal",()=>this.#mt(t))),this.session.onError(t=>this.#o("session",t)),this.session.start(),this.#V(),this.#k(this.options.presenceIntervalMs,.3,()=>this.#V())}#V(){if(!(!this.session||this.stopped))try{this.session.announcePresence({role:"viewer",transports:[{type:zr,publicKey:this.session.pubkey,...this.#L()?{obj:2}:{}}],have:this.#p()?[...this.held.keys()].slice(-8):[],open:this.#ht(),...this.#ne()?{ticket:this.#ne()}:{}}),this.counters.presenceSent+=1;for(let[e,t]of this.renditions){if(t{this.reannounceTimer=null,this.#V()})}#q(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.#q(t,e.rendition)||e.keys.some(r=>t.have.has(r))))}#Re(e){let t=[...this.links.values()].filter(r=>this.#q(r,e.rendition));return t.length>0&&t.every(r=>this.discovery.stale(e,r.pubkey))}#ct(e){return[...this.links.values()].filter(t=>this.#q(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()||we(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 Qi([...this.links.values()].filter(r=>!t.some(s=>!this.discovery.stale(s,r.pubkey)&&(this.#q(r,s.rendition)||s.keys.some(i=>r.have.has(i))))),{...this.options,banned:this.banned,tier:r=>this.#Ie(r)})}#F(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.#F(t))}#te(){if(this.stopped||this.options.mode!=="peer-first"||(this.#j(),!this.#re()))return;for(let i of this.discovery.contexts.values())this.discovery.rearm(i,()=>this.#ct(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.#F(s))),this.#r("discovery",()=>this.#ie(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 Qi(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}`]++}#ht(){return this.#j(),this.discovery.reserved()?!1:this.#_()||this.links.size>=2&&!!this.#Oe()}#ut(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:zr,requestId:r,payload:s}),this.counters.signalsSent+=1,!0)}catch(i){return this.counters.publishErrors+=1,this.#o("signal-send",i),!1}}#ft(e){return yl(e,this.options)}#pt(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.#te();return}if(!(this.links.has(e)||this.dials.has(e)||this.banned.has(e)||!this.#_()))return this.cooldowns.delete(e),this.#ie(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.#r("referral",()=>this.#ie(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"}#ne(){return we(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(!we(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 at(a=>{try{let l=Xi.includes(r)?r:"other";this.admissionCallCounters[l]=Ve(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,...we(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.#r("admission-refresh",async()=>{await this.#x(e,o.ticket,"refresh")&&o.open!==null&&this.#$(e,o.open)})}),this.admissionChecks.set(e,i),i.promise}async#gt({from:e,payload:t}){if(this.stopped||t.role!=="viewer")return;let r=t.transports.find(l=>l.type===zr);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.#te());let s=this.links.has(e)||this.dials.has(e),i=this.admitted.get(e);i&&we(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.#A();return}if(!s&&(this.#D(e)||!this.#_()||!this.#re())){o&&t.open!==null&&this.#$(e,t.open);return}let a=this.admissionChecks.get(e);if(s&&a){we(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.#A(),!(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.#re())return this.#ie(e)}))}#g(e,t,r,s){try{if(!Fr[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]=Ve(this.transportCounters[t][r]),this.transportRecords.length===64&&(this.transportRecords.shift(),this.transportDropped=Ve(this.transportDropped)),this.transportRecords.push(a)}catch{}}#Ne(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}}#Pe(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,Fr[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))}#se(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{}}#He(e,t,r){!r&&e.discovery&&(this.#F(e.discovery.window,!1),e.discovery=null),e.negotiation&&(e.negotiation.superseded=!0),this.#se(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}#De(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.#r("link-open",()=>this.#yt(e,t,r))},r.addEventListener("open",t.onOpen),r.readyState==="open"&&t.onOpen()}}#Ue(e,t){this.#u(e,t)&&(t.ready=!0,t.channel?.readyState==="open"&&t.onOpen())}async#ie(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.#re()){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.#Pe(!0),s=gl(),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.#He(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.#De(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 Ji(r,1200,o.controller.signal,h=>{i.negotiation===o&&!o.superseded&&this.#Ne(r,"offer",h)}),!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.#ne(),c=this.#ue(e,"offer",s,{sdp:r.localDescription.sdp,peers:this.links.size,...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.#se(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.#te()}async#mt({from:e,payload:t}){if(this.stopped||t.transport!==zr)return;let r=typeof t.payload?.sdp=="string"?t.payload.sdp:"";if(t.type==="answer"){let u=this.dials.get(e);if(!u?.outgoing||u.requestId!==t.requestId||!r)return;let p=u.negotiation;if(p.answerPending)return;if(this.#g(u.pc,"answer-received","authenticated"),!await this.#x(e,we(t.payload.ticket)?t.payload.ticket:null,"answerIncoming")){this.#u(u,p)&&this.#m(u,"failed",0,"admission");return}if(!this.#u(u,p)||!u.outgoing||u.requestId!==t.requestId||p.answerPending)return;p.answerPending=!0,this.#g(u.pc,"answer-admitted","accepted"),u.answerAt=I();try{await this.#fe(u,p,async()=>{await u.pc.setRemoteDescription({type:"answer",sdp:r}),this.#u(u,p)&&(this.#g(u.pc,"remote-installed","answer"),this.#Ue(u,p))})}catch(g){this.#u(u,p)&&(this.#o("answer",g),this.#m(u,"failed"))}return}if(t.type==="reject"){let u=this.dials.get(e);if(!u?.outgoing||u.requestId!==t.requestId)return;let p=this.#ft(t.payload);this.#m(u,"rejected",p.retryAfterMs),this.#$(e,!1),this.#pt(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,we(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.#ut(t.payload?.peers,t.payload?.requestedKey)){this.counters.offersRefused+=1,this.counters.evictionsUnavailable+=1,this.#ue(e,"reject",t.requestId,this.#dt(e));return}let u=this.#Pe(!1);a={pubkey:e,pc:u,startedAt:I(),offerSentAt:I()},this.dials.set(e,a),a.timer=this.#h(this.options.dialTimeoutMs,()=>this.#m(a,"timeout"))}let c=a.pc,h=this.#He(a,t.requestId,!1);l&&this.#g(c,"negotiation","glare-yield"),this.#g(c,"offer-admitted","accepted"),h.onDataChannel=u=>this.#De(a,h,u.channel),c.addEventListener("datachannel",h.onDataChannel);try{await this.#fe(a,h,async()=>{if(l){if(!await this.#x(e,we(t.payload.ticket)?t.payload.ticket:null,"glareBeforeRollback")){this.#u(a,h)&&this.#m(a,"failed",0,"admission");return}if(!this.#u(a,h))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,h)))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,we(t.payload.ticket)?t.payload.ticket:null,"glareAfterRollback")){this.#u(a,h)&&this.#m(a,"failed",0,"admission");return}if(!this.#u(a,h))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,h))return;this.#g(c,"remote-installed","offer");let u=await c.createAnswer();if(!this.#u(a,h)||(await c.setLocalDescription(u),!this.#u(a,h))||(await Ji(c,1200,h.controller.signal,f=>{a.negotiation===h&&!h.superseded&&this.#Ne(c,"answer",f)}),!this.#u(a,h)))return;if(!await this.#x(e,we(t.payload.ticket)?t.payload.ticket:null,"answerBeforeSend")){this.#u(a,h)&&this.#m(a,"failed",0,"admission");return}if(!this.#u(a,h))return;let p=this.#ne(),g=this.#ue(e,"answer",t.requestId,{sdp:c.localDescription.sdp,...p?{ticket:p}:{}});this.#g(c,g?"signal-send":"signal-failed","answer"),g?(this.counters.offersAccepted+=1,this.#Ue(a,h)):this.#m(a,"failed")})}catch(u){this.#u(a,h)&&(this.#o("offer",u),this.#m(a,"failed"))}}async#yt(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.#se(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.#F(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&&Ke(this.signallingSamples,I()-e.offerSentAt);let i=this.#at({pubkey:e.pubkey,pc:e.pc,channel:r,maxSegmentBytes:this.options.maxSegmentBytes,onRequest:(a,l,c)=>this.#nt(a,l,c),onHaveChange:(a,l)=>{for(let c of[...this.haveWaiters])c(l);this.#A()},onScheduleChange:()=>{for(let a of[...this.haveWaiters])a();for(let a of[...this.peerLeaseWaiters])a();this.#A()},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.#r("reannounce",()=>this.#Be()))}});this.links.set(e.pubkey,i),this.#qe(e.pubkey),this.#A(),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 pl(e.pc);this.pairTypes[o]=(this.pairTypes[o]||0)+1;for(let a of[...this.haveWaiters])a()}};var Mh=Object.freeze({version:"0.4.4",sourceCommit:"167b1c971c94456983da28d32dede00cd4c3123b"});export{Si as KIND_SEGMENT_COMMITMENT,ki as commitmentContent,xt as commitmentPieceSize,bl as createHlsSwarm,wr as finalizeEvent,Vt as generateSecretKey,Yt as matchFilter,Mh as relayswarmBuild,_t as segmentMediaContext,$t as verifyEvent}; +${s}${i}`,key:null,sampled:Math.random()this.#et(o)),o}catch(t){return this.#o("begin-race",t),null}}async#et(e){if(e.keyPromise=Nt($i.encode(e.keyText)),e.key=await e.keyPromise,this.stopped)return;if(!e.sampled||!this.options.serveOnCellular&&Pt())return e.peerDone=!0,e.skipPeers=!0,this.#r("settle",()=>this.#ee(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.#r("settle",()=>this.#ee(e))}#Q(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#tt(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,Ke(this.originLatencySamples,i-e.t0),e.sampled&&(e.originDigest=await Nt(s)),e.originDone=!0,await e.keyPromise,!this.stopped&&(s&&this.#T(e.key,s),this.#r("settle",()=>this.#ee(e)))}#z(e){e.settled||e.originDone||(e.controller.abort(),e.originDone=!0,e.originFailed=!0,this.#r("settle",()=>this.#ee(e)))}async#ee(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 Nt(e.peerBytes)!==e.originDigest){this.#R(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.#R(e.peerLink,e.requestMs,e.peerBytes.byteLength),this.firstPeerSegmentAtMs===null&&(this.firstPeerSegmentAtMs=Date.now()-this.startedAt),Ke(this.peerLatencySamples,s),t.bytesFromPeers+=e.peerBytes.byteLength,s<=this.options.originFallbackMs?(t.peerInTime+=1,t.peerInTimeBytes+=e.peerBytes.byteLength):t.peerLate+=1}#T(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)}#rt(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||!Pt())}#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#nt(e,t,r=null){if(this.uploadPacer)return this.#st(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 h=xt(i.byteLength),u=r.start*h,p=Math.min(r.end*h,i.byteLength);if(!(ua)return this.#y("session-allowance"),null;let l=[...this.links.values()].filter(h=>h!==e&&(h.outboundInFlight>0||Date.now()-h.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:u}),this.lifecycle.signal,this.options.admissionTimeoutMs)===!0}catch{this.#o("upload-reservation")}if(!h||this.stopped||e.closed||this.options.serve!==!0||!this.options.serveOnCellular&&Pt())return h||(this.uploadQuotaBytes-=o),this.#y(h?"reservation-inactive":"reservation-refused"),null}if(this.counters.bytesUploaded+=o,this.counters.uploadsServed+=1,this.options.testHooks?.corruptUploads){let h=i.slice();return h[h.length>>1]^=255,h}return i}#y(e){this.counters.uploadsRefused+=1,this.uploadRefusalCounters[e]=Ve(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&&Pt()||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(!h())return null;let u=this.admissionChecks.get(e.pubkey)?.ticket??this.admitted.get(e.pubkey)?.ticket;if(this.options.admit&&!await at(()=>this.#x(e.pubkey,u,"upload"),c,this.options.admissionTimeoutMs))return this.#y("admission"),e.close("admission"),null;if(!h())return null;if(this.uploadQuotaBytes+=i.charge,o=!0,this.options.reserveUploadBytes){try{a=await at(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(!h()||this.options.admit&&this.admitted.get(e.pubkey)?.ticket!==u)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#it(){this.coreState="loading";try{let e=await Ni(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.#ot(e)}catch(e){this.coreState="failed",this.options.transferWorkerUrl!==void 0&&(this.transferWorkerState="failed",this.transferWorkerReason="core-failed"),this.#o("core",e)}}async#ot(e){this.transferWorkerState="loading";try{let t=this.options.WorkerImpl,r=await Hi({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.#L();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()}#L(){return this.options.multiHolder===!0&&this.options.mode==="peer-first"&&!!this.core&&!this.core.retired&&this.coreLinks.js===0}#at(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 ot(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,Mi(e,t)}async#lt(){let e=this.options.secretKey||Vt();if(this.pool=new _r(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 Or({pool:this.pool,swarmId:this.options.swarmId,secretKey:e,maxEventAgeSeconds:60}),this.session.onPresence(t=>this.#r("presence",()=>this.#gt(t))),this.session.onSignal(t=>this.#r("signal",()=>this.#mt(t))),this.session.onError(t=>this.#o("session",t)),this.session.start(),this.#V(),this.#k(this.options.presenceIntervalMs,.3,()=>this.#V())}#V(){if(!(!this.session||this.stopped))try{this.session.announcePresence({role:"viewer",transports:[{type:zr,publicKey:this.session.pubkey,...this.#L()?{obj:2}:{}}],have:this.#p()?[...this.held.keys()].slice(-8):[],open:this.#ht(),...this.#ne()?{ticket:this.#ne()}:{}}),this.counters.presenceSent+=1;for(let[e,t]of this.renditions){if(t{this.reannounceTimer=null,this.#V()})}#q(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.#q(t,e.rendition)||e.keys.some(r=>t.have.has(r))))}#Re(e){let t=[...this.links.values()].filter(r=>this.#q(r,e.rendition));return t.length>0&&t.every(r=>this.discovery.stale(e,r.pubkey))}#ct(e){return[...this.links.values()].filter(t=>this.#q(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()||we(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 Qi([...this.links.values()].filter(r=>!t.some(s=>!this.discovery.stale(s,r.pubkey)&&(this.#q(r,s.rendition)||s.keys.some(i=>r.have.has(i))))),{...this.options,banned:this.banned,tier:r=>this.#Ie(r)})}#F(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.#F(t))}#te(){if(this.stopped||this.options.mode!=="peer-first"||(this.#j(),!this.#re()))return;for(let i of this.discovery.contexts.values())this.discovery.rearm(i,()=>this.#ct(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.#F(s))),this.#r("discovery",()=>this.#ie(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 Qi(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}`]++}#ht(){return this.#j(),this.discovery.reserved()?!1:this.#_()||this.links.size>=2&&!!this.#Oe()}#ut(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:zr,requestId:r,payload:s}),this.counters.signalsSent+=1,!0)}catch(i){return this.counters.publishErrors+=1,this.#o("signal-send",i),!1}}#ft(e){return yl(e,this.options)}#pt(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.#te();return}if(!(this.links.has(e)||this.dials.has(e)||this.banned.has(e)||!this.#_()))return this.cooldowns.delete(e),this.#ie(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.#r("referral",()=>this.#ie(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"}#ne(){return we(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(!we(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 at(a=>{try{let l=Xi.includes(r)?r:"other";this.admissionCallCounters[l]=Ve(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,...we(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.#r("admission-refresh",async()=>{await this.#x(e,o.ticket,"refresh")&&o.open!==null&&this.#$(e,o.open)})}),this.admissionChecks.set(e,i),i.promise}async#gt({from:e,payload:t}){if(this.stopped||t.role!=="viewer")return;let r=t.transports.find(l=>l.type===zr);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.#te());let s=this.links.has(e)||this.dials.has(e),i=this.admitted.get(e);i&&we(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.#A();return}if(!s&&(this.#D(e)||!this.#_()||!this.#re())){o&&t.open!==null&&this.#$(e,t.open);return}let a=this.admissionChecks.get(e);if(s&&a){we(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.#A(),!(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.#re())return this.#ie(e)}))}#g(e,t,r,s){try{if(!Fr[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]=Ve(this.transportCounters[t][r]),this.transportRecords.length===64&&(this.transportRecords.shift(),this.transportDropped=Ve(this.transportDropped)),this.transportRecords.push(a)}catch{}}#Ne(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}}#Pe(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,Fr[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))}#se(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{}}#He(e,t,r){!r&&e.discovery&&(this.#F(e.discovery.window,!1),e.discovery=null),e.negotiation&&(e.negotiation.superseded=!0),this.#se(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}#De(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.#r("link-open",()=>this.#yt(e,t,r))},r.addEventListener("open",t.onOpen),r.readyState==="open"&&t.onOpen()}}#Ue(e,t){this.#u(e,t)&&(t.ready=!0,t.channel?.readyState==="open"&&t.onOpen())}async#ie(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.#re()){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.#Pe(!0),s=gl(),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.#He(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.#De(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 Ji(r,1200,o.controller.signal,h=>{i.negotiation===o&&!o.superseded&&this.#Ne(r,"offer",h)}),!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.#ne(),c=this.#ue(e,"offer",s,{sdp:r.localDescription.sdp,peers:this.links.size,...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.#se(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.#te()}async#mt({from:e,payload:t}){if(this.stopped||t.transport!==zr)return;let r=typeof t.payload?.sdp=="string"?t.payload.sdp:"";if(t.type==="answer"){let u=this.dials.get(e);if(!u?.outgoing||u.requestId!==t.requestId||!r)return;let p=u.negotiation;if(p.answerPending)return;if(this.#g(u.pc,"answer-received","authenticated"),!await this.#x(e,we(t.payload.ticket)?t.payload.ticket:null,"answerIncoming")){this.#u(u,p)&&this.#m(u,"failed",0,"admission");return}if(!this.#u(u,p)||!u.outgoing||u.requestId!==t.requestId||p.answerPending)return;p.answerPending=!0,this.#g(u.pc,"answer-admitted","accepted"),u.answerAt=I();try{await this.#fe(u,p,async()=>{await u.pc.setRemoteDescription({type:"answer",sdp:r}),this.#u(u,p)&&(this.#g(u.pc,"remote-installed","answer"),this.#Ue(u,p))})}catch(g){this.#u(u,p)&&(this.#o("answer",g),this.#m(u,"failed"))}return}if(t.type==="reject"){let u=this.dials.get(e);if(!u?.outgoing||u.requestId!==t.requestId)return;let p=this.#ft(t.payload);this.#m(u,"rejected",p.retryAfterMs),this.#$(e,!1),this.#pt(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,we(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.#ut(t.payload?.peers,t.payload?.requestedKey)){this.counters.offersRefused+=1,this.counters.evictionsUnavailable+=1,this.#ue(e,"reject",t.requestId,this.#dt(e));return}let u=this.#Pe(!1);a={pubkey:e,pc:u,startedAt:I(),offerSentAt:I()},this.dials.set(e,a),a.timer=this.#h(this.options.dialTimeoutMs,()=>this.#m(a,"timeout"))}let c=a.pc,h=this.#He(a,t.requestId,!1);l&&this.#g(c,"negotiation","glare-yield"),this.#g(c,"offer-admitted","accepted"),h.onDataChannel=u=>this.#De(a,h,u.channel),c.addEventListener("datachannel",h.onDataChannel);try{await this.#fe(a,h,async()=>{if(l){if(!await this.#x(e,we(t.payload.ticket)?t.payload.ticket:null,"glareBeforeRollback")){this.#u(a,h)&&this.#m(a,"failed",0,"admission");return}if(!this.#u(a,h))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,h)))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,we(t.payload.ticket)?t.payload.ticket:null,"glareAfterRollback")){this.#u(a,h)&&this.#m(a,"failed",0,"admission");return}if(!this.#u(a,h))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,h))return;this.#g(c,"remote-installed","offer");let u=await c.createAnswer();if(!this.#u(a,h)||(await c.setLocalDescription(u),!this.#u(a,h))||(await Ji(c,1200,h.controller.signal,f=>{a.negotiation===h&&!h.superseded&&this.#Ne(c,"answer",f)}),!this.#u(a,h)))return;if(!await this.#x(e,we(t.payload.ticket)?t.payload.ticket:null,"answerBeforeSend")){this.#u(a,h)&&this.#m(a,"failed",0,"admission");return}if(!this.#u(a,h))return;let p=this.#ne(),g=this.#ue(e,"answer",t.requestId,{sdp:c.localDescription.sdp,...p?{ticket:p}:{}});this.#g(c,g?"signal-send":"signal-failed","answer"),g?(this.counters.offersAccepted+=1,this.#Ue(a,h)):this.#m(a,"failed")})}catch(u){this.#u(a,h)&&(this.#o("offer",u),this.#m(a,"failed"))}}async#yt(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.#se(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.#F(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&&Ke(this.signallingSamples,I()-e.offerSentAt);let i=this.#at({pubkey:e.pubkey,pc:e.pc,channel:r,maxSegmentBytes:this.options.maxSegmentBytes,onRequest:(a,l,c)=>this.#nt(a,l,c),onHaveChange:(a,l)=>{for(let c of[...this.haveWaiters])c(l);this.#A()},onScheduleChange:()=>{for(let a of[...this.haveWaiters])a();for(let a of[...this.peerLeaseWaiters])a();this.#A()},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.#r("reannounce",()=>this.#Be()))}});this.links.set(e.pubkey,i),this.#qe(e.pubkey),this.#A(),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 pl(e.pc);this.pairTypes[o]=(this.pairTypes[o]||0)+1;for(let a of[...this.haveWaiters])a()}};var Mh=Object.freeze({version:"0.4.4",sourceCommit:"f923058503778dea2427a81330da04cce80a95c2"});export{Si as KIND_SEGMENT_COMMITMENT,ki as commitmentContent,xt as commitmentPieceSize,bl as createHlsSwarm,wr as finalizeEvent,Vt as generateSecretKey,Yt as matchFilter,Mh as relayswarmBuild,_t as segmentMediaContext,$t 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 9744b5d..0c501c3 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/167b1c971c94456983da28d32dede00cd4c3123b +https://github.com/forgesworn/relayswarm/tree/f923058503778dea2427a81330da04cce80a95c2 MIT License diff --git a/site/vendor/relayswarm-transfer-worker.js b/site/vendor/relayswarm-transfer-worker.js index 5fbd12a..2820c81 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 167b1c971c94456983da28d32dede00cd4c3123b. See media-peer-demo.NOTICE.txt. */ +/*! RelaySwarm 0.4.4 transfer worker; public source f923058503778dea2427a81330da04cce80a95c2. 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}; From bf8a64c366e8626c3dacb6fc2e6d497617fa1620 Mon Sep 17 00:00:00 2001 From: TheCryptoDonkey <147930957+TheCryptoDonkey@users.noreply.github.com> Date: Tue, 27 Oct 2026 14:19:49 +0000 Subject: [PATCH 3/3] chore: pin portable origin handoff verification source --- docs/media-showcase.md | 4 ++-- scripts/build-media-peer-demo.mjs | 2 +- site/llms.txt | 2 +- site/vendor/media-peer-demo.NOTICE.txt | 2 +- site/vendor/media-peer-demo.build.json | 8 ++++---- site/vendor/media-peer-demo.js | 4 ++-- site/vendor/relayswarm-core.NOTICE.txt | 2 +- site/vendor/relayswarm-transfer-worker.js | 2 +- 8 files changed, 13 insertions(+), 13 deletions(-) diff --git a/docs/media-showcase.md b/docs/media-showcase.md index 07d237f..8ac4dc3 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 `f923058503778dea2427a81330da04cce80a95c2` -([source change](https://github.com/forgesworn/relayswarm/commit/f923058503778dea2427a81330da04cce80a95c2)). +The player pins RelaySwarm source `b75d71bde9aa836e45b27d26d569353530a955d2` +([source change](https://github.com/forgesworn/relayswarm/commit/b75d71bde9aa836e45b27d26d569353530a955d2)). 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 permits one extra contiguous startup fragment when the diff --git a/scripts/build-media-peer-demo.mjs b/scripts/build-media-peer-demo.mjs index f36c847..8ddaefb 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 = 'f923058503778dea2427a81330da04cce80a95c2'; +const SOURCE = 'b75d71bde9aa836e45b27d26d569353530a955d2'; const sha = bytes => createHash('sha256').update(bytes).digest('hex'); const root = fileURLToPath(new URL('../', import.meta.url)); diff --git a/site/llms.txt b/site/llms.txt index 2eaad8d..fd4da29 100644 --- a/site/llms.txt +++ b/site/llms.txt @@ -7,7 +7,7 @@ - [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 f923058503778dea2427a81330da04cce80a95c2 (package version 0.4.4), retaining bounded rolling startup planning, sustainable peer waits and range-sized WASM uploads. 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. 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 b75d71bde9aa836e45b27d26d569353530a955d2 (package version 0.4.4), retaining bounded rolling startup planning, sustainable peer waits and range-sized WASM uploads. 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. 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. - [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/vendor/media-peer-demo.NOTICE.txt b/site/vendor/media-peer-demo.NOTICE.txt index cee03fb..3b8690b 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/f923058503778dea2427a81330da04cce80a95c2 +https://github.com/forgesworn/relayswarm/tree/b75d71bde9aa836e45b27d26d569353530a955d2 MIT License diff --git a/site/vendor/media-peer-demo.build.json b/site/vendor/media-peer-demo.build.json index c1076da..8ebabc1 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": "f923058503778dea2427a81330da04cce80a95c2", + "sourceCommit": "b75d71bde9aa836e45b27d26d569353530a955d2", "version": "0.4.4", - "sourceArchiveSha256": "0f5953fbe800cef0e2b1be891a251b5ecbb5610b957d123ac6fab61e8f6f644f", + "sourceArchiveSha256": "6947da2981bfbee0ea6709bdecd3ac37760d4ff8674c14aa540ecc74e241495a", "packageLockSha256": "18a91b8d697ebcab1d259d4de876167dcbd4d47fc3c82196d179c4c490adca4a", "bundle": "media-peer-demo.js", - "bundleSha256": "fba69c6941b377b9e209a6d7a292535422f68fd068c16b340cfcf1ee4b74f96f", + "bundleSha256": "d00d0ce012bb9963aede85581b63cfc47287eb2c1236467e3d6a0b041b095f1e", "bundleBytes": 260708, "transferWorker": { "file": "relayswarm-transfer-worker.js", "bytes": 7074, - "sha256": "548e4205bd2594fdf5a86d6d1800fa566f49c380e15c425e764a3863b0b19ca2", + "sha256": "9ba3d99b011e98b983748cc2c806541e56d07e5c8854d0c1c3e3cf30247880f3", "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 a4cf1cf..7afd36f 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 f923058503778dea2427a81330da04cce80a95c2. See media-peer-demo.NOTICE.txt. */ +/*! RelaySwarm 0.4.4; public source b75d71bde9aa836e45b27d26d569353530a955d2. See media-peer-demo.NOTICE.txt. */ function Zn(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 Xn(n){return{samples:n.length,offsetSeconds:n.length?Math.round(Math.max(...n)/1e3):null}}function Dt(n){return n instanceof Uint8Array||ArrayBuffer.isView(n)&&n.constructor.name==="Uint8Array"}function He(n,e=""){if(!Number.isSafeInteger(n)||n<0){let t=e&&`"${e}" `;throw new Error(`${t}expected integer >= 0, got ${n}`)}}function se(n,e,t=""){let r=Dt(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");He(n.outputLen),He(n.blockLen)}function Et(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 Qn(n,e){se(n,void 0,"digestInto() output");let t=e.outputLen;if(n.length='+t)}function Ge(...n){for(let e=0;e>>e}var es=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",to=Array.from({length:256},(n,e)=>e.toString(16).padStart(2,"0"));function De(n){if(se(n),es)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 Oe(n){if(typeof n!="string")throw new Error("hex string expected, got "+typeof n);if(es)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 rs=n=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,n])});function ns(n,e,t){return n&e^~n&t}function ss(n,e,t){return n&e^n&t^e&t}var or=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=ir(this.buffer)}update(e){Et(this),se(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 u=o;uh.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u>>3,m=ze(g,17)^ze(g,19)^g>>>10;tt[u]=m+tt[u-7]+f+tt[u-16]|0}let{A:r,B:s,C:i,D:o,E:a,F:l,G:c,H:h}=this;for(let u=0;u<64;u++){let p=ze(a,6)^ze(a,11)^ze(a,25),g=h+p+ns(a,l,c)+ro[u]+tt[u]|0,m=(ze(r,2)^ze(r,13)^ze(r,22))+ss(r,s,i)|0;h=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,h=h+this.H|0,this.set(r,s,i,o,a,l,c,h)}roundClean(){Ge(tt)}destroy(){this.set(0,0,0,0,0,0,0,0),Ge(this.buffer)}},Vr=class extends Kr{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=ts(()=>new Vr,rs(1));var Gr=BigInt(0),$r=BigInt(1);function Ut(n,e=""){if(typeof n!="boolean"){let t=e&&`"${e}" `;throw new Error(t+"expected boolean, got type="+typeof n)}return n}function is(n){if(typeof n=="bigint"){if(!ar(n))throw new Error("positive bigint expected, got "+n)}else He(n);return n}function zt(n){let e=is(n).toString(16);return e.length&1?"0"+e:e}function os(n){if(typeof n!="string")throw new Error("hex string expected, got "+typeof n);return n===""?Gr:BigInt("0x"+n)}function rt(n){return os(De(n))}function Yr(n){return os(De(no(se(n)).reverse()))}function lr(n,e){He(e),n=is(n);let t=Oe(n.toString(16).padStart(e*2,"0"));if(t.length!==e)throw new Error("number too large");return t}function Zr(n,e){return lr(n,e).reverse()}function no(n){return Uint8Array.from(n)}function as(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 ar=n=>typeof n=="bigint"&&Gr<=n;function so(n,e,t){return ar(n)&&ar(e)&&ar(t)&&e<=n&&nGr;n>>=$r,e+=1);return e}var qt=n=>($r<new Uint8Array(y),s=Uint8Array.of(),i=Uint8Array.of(0),o=Uint8Array.of(1),a=1e3,l=r(n),c=r(n),h=0,u=()=>{l.fill(1),c.fill(0),h=0},p=(...y)=>t(c,Se(l,...y)),g=(y=s)=>{c=p(i,y),l=p(),y.length!==0&&(c=p(o,y),l=p())},f=()=>{if(h++>=a)throw new Error("drbg: tried max amount of iterations");let y=0,v=[];for(;y{u(),g(y);let b;for(;!(b=v(f()));)g();return u(),b}}function Ft(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 Jr(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 Le=BigInt(0),Re=BigInt(1),gt=BigInt(2),ds=BigInt(3),fs=BigInt(4),ps=BigInt(5),io=BigInt(7),gs=BigInt(8),oo=BigInt(9),ms=BigInt(16);function qe(n,e){let t=n%e;return t>=Le?t:e+t}function Ne(n,e,t){let r=n;for(;e-- >Le;)r*=r,r%=t;return r}function hs(n,e){if(n===Le)throw new Error("invert: expected non-zero number");if(e<=Le)throw new Error("invert: expected positive modulus, got "+e);let t=qe(n,e),r=e,s=Le,i=Re,o=Re,a=Le;for(;t!==Le;){let c=r/t,h=r%t,u=s-o*c,p=i-a*c;r=t,t=h,s=o,i=a,o=u,a=p}if(r!==Re)throw new Error("invert: does not exist");return qe(s,e)}function en(n,e,t){if(!n.eql(n.sqr(e),t))throw new Error("Cannot find square root")}function ys(n,e){let t=(n.ORDER+Re)/fs,r=n.pow(e,t);return en(n,r,e),r}function ao(n,e){let t=(n.ORDER-ps)/gs,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 en(n,a,e),a}function lo(n){let e=At(n),t=bs(n),r=t(e,e.neg(e.ONE)),s=t(e,r),i=t(e,e.neg(r)),o=(n+io)/ms;return(a,l)=>{let c=a.pow(l,o),h=a.mul(c,r),u=a.mul(c,s),p=a.mul(c,i),g=a.eql(a.sqr(h),l),f=a.eql(a.sqr(u),l);c=a.cmov(c,h,g),h=a.cmov(p,u,f);let m=a.eql(a.sqr(h),l),y=a.cmov(c,h,m);return en(a,y,l),y}}function bs(n){if(n1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return ys;let i=s.pow(r,e),o=(e+Re)/gt;return function(l,c){if(l.is0(c))return c;if(us(l,c)!==1)throw new Error("Cannot find square root");let h=t,u=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===h)throw new Error("Cannot find square root");let y=Re<(r[s]="function",r),e);return Ft(n,t),n}function uo(n,e,t){if(tLe;)t&Re&&(r=n.mul(r,s)),s=n.sqr(s),t>>=Re;return r}function cr(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 us(n,e){let t=(n.ORDER-Re)/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 fo(n,e){e!==void 0&&He(e);let t=e!==void 0?e:n.toString(2).length,r=Math.ceil(t/8);return{nBitLength:t,nByteLength:r}}var Qr=class{ORDER;BITS;BYTES;isLE;ZERO=Le;ONE=Re;_lengths;_sqrt;_mod;constructor(e,t={}){if(e<=Le)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}=fo(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 qe(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return Le<=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?Yr(e):rt(e);if(a&&(l=qe(l,o)),!t&&!this.isValid(l))throw new Error("invalid field element: outside of range 0..ORDER");return l}invertBatch(e){return cr(this,e)}cmov(e,t,r){return r?t:e}};function At(n,e={}){return new Qr(n,e)}function ws(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 rn(n){let e=ws(n);return e+Math.ceil(e/2)}function hr(n,e,t=!1){se(n);let r=n.length,s=ws(e),i=rn(e);if(r<16||r1024)throw new Error("expected "+i+"-1024 bytes of input, got "+r);let o=t?Yr(n):rt(n),a=qe(o,e-Re)+Re;return t?Zr(a,s):lr(a,s)}var kt=BigInt(0),mt=BigInt(1);function jt(n,e){let t=e.negate();return n?t:e}function an(n,e){let t=cr(n.Fp,e.map(r=>r.Z));return e.map((r,s)=>n.fromAffine(r.toAffine(t[s])))}function Es(n,e){if(!Number.isSafeInteger(n)||n<=0||n>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+n)}function nn(n,e){Es(n,e);let t=Math.ceil(e/n)+1,r=2**(n-1),s=2**n,i=qt(n),o=BigInt(n);return{windows:t,windowSize:r,mask:i,maxNumber:s,shiftBy:o}}function vs(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,h=c+Math.abs(a)-1,u=a===0,p=a<0,g=e%2!==0;return{nextN:l,offset:h,isZero:u,isNeg:p,isNegF:g,offsetF:c}}var sn=new WeakMap,As=new WeakMap;function on(n){return As.get(n)||1}function xs(n){if(n!==kt)throw new Error("invalid wNAF")}var ur=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>kt;)t&mt&&(r=r.add(s)),s=s.double(),t>>=mt;return r}precomputeWindow(e,t){let{windows:r,windowSize:s}=nn(t,this.bits),i=[],o=e,a=o;for(let l=0;lkt||r>kt;)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 Ss(n,e,t){if(e){if(e.ORDER!==n)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return tn(e),e}else return At(n,{isLE:t})}function Ms(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>kt))throw new Error(`CURVE.${l} must be positive bigint`)}let s=Ss(e.p,t.Fp,r),i=Ss(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 dr(n,e){return function(r){let s=n(r);return{secretKey:s,publicKey:e(s)}}}var fr=class{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,t){if(pt(e),se(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 fr(n,e).update(t).digest();nt.create=(n,e)=>new fr(n,e);var Bs=(n,e)=>(n+(n>=0?e:-e)/Rs)/e;function po(n,e,t){let[[r,s],[i,o]]=e,a=Bs(o*n,t),l=Bs(-s*n,t),c=n-a*r-l*i,h=-a*s-l*o,u=c=g||h=g)throw new Error("splitScalar (endomorphism): failed, k="+n);return{k1neg:u,k1:c,k2neg:p,k2:h}}function cn(n){if(!["compact","recovered","der"].includes(n))throw new Error('Signature format must be "compact", "recovered", or "der"');return n}function ln(n,e){let t={};for(let r of Object.keys(e))t[r]=n[r]===void 0?e[r]:n[r];return Ut(t.lowS,"lowS"),Ut(t.prehash,"prehash"),t.format!==void 0&&cn(t.format),t}var hn=class extends Error{constructor(e=""){super(e)}},st={Err:hn,_tlv:{encode:(n,e)=>{let{Err:t}=st;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=zt(r);if(s.length/2&128)throw new t("tlv.encode: long form length too big");let i=r>127?zt(s.length/2|128):"";return zt(n)+i+s+e},decode(n,e){let{Err:t}=st,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 h of c)o=o<<8|h;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}=st;if(n{let{X:A,Y:x,Z:R}=d;if(r.eql(R,r.ONE))return{x:A,y:x};let P=d.is0();w==null&&(w=P?r.ONE:r.inv(R));let N=r.mul(A,w),M=r.mul(x,w),H=r.mul(R,w);if(P)return{x:r.ZERO,y:r.ZERO};if(!r.eql(H,r.ONE))throw new Error("invZ was invalid");return{x:N,y:M}}),L=Jr(d=>{if(d.is0()){if(e.allowInfinityPoint&&!r.is0(d.Y))return;throw new Error("bad point: ZERO")}let{x:w,y:A}=d.toAffine();if(!r.isValid(w)||!r.isValid(A))throw new Error("bad point: x or y not field elements");if(!y(w,A))throw new Error("bad point: equation left != right");if(!d.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function U(d,w,A,x,R){return A=new C(r.mul(A.X,d),A.Y,A.Z),w=jt(x,w),A=jt(R,A),w.add(A)}class C{static BASE=new C(i.Gx,i.Gy,r.ONE);static ZERO=new C(r.ZERO,r.ONE,r.ZERO);static Fp=r;static Fn=s;X;Y;Z;constructor(w,A,x){this.X=T("x",w),this.Y=T("y",A,!0),this.Z=T("z",x),Object.freeze(this)}static CURVE(){return i}static fromAffine(w){let{x:A,y:x}=w||{};if(!w||!r.isValid(A)||!r.isValid(x))throw new Error("invalid affine point");if(w instanceof C)throw new Error("projective point not allowed");return r.is0(A)&&r.is0(x)?C.ZERO:new C(A,x,r.ONE)}static fromBytes(w){let A=C.fromAffine(f(se(w,void 0,"point")));return A.assertValidity(),A}static fromHex(w){return C.fromBytes(Oe(w))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(w=8,A=!0){return O.createCache(this,w),A||this.multiply(pr),this}assertValidity(){L(this)}hasEvenY(){let{y:w}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(w)}equals(w){B(w);let{X:A,Y:x,Z:R}=this,{X:P,Y:N,Z:M}=w,H=r.eql(r.mul(A,M),r.mul(P,R)),D=r.eql(r.mul(x,M),r.mul(N,R));return H&&D}negate(){return new C(this.X,r.neg(this.Y),this.Z)}double(){let{a:w,b:A}=i,x=r.mul(A,pr),{X:R,Y:P,Z:N}=this,M=r.ZERO,H=r.ZERO,D=r.ZERO,q=r.mul(R,R),ee=r.mul(P,P),j=r.mul(N,N),V=r.mul(R,P);return V=r.add(V,V),D=r.mul(R,N),D=r.add(D,D),M=r.mul(w,D),H=r.mul(x,j),H=r.add(M,H),M=r.sub(ee,H),H=r.add(ee,H),H=r.mul(M,H),M=r.mul(V,M),D=r.mul(x,D),j=r.mul(w,j),V=r.sub(q,j),V=r.mul(w,V),V=r.add(V,D),D=r.add(q,q),q=r.add(D,q),q=r.add(q,j),q=r.mul(q,V),H=r.add(H,q),j=r.mul(P,N),j=r.add(j,j),q=r.mul(j,V),M=r.sub(M,q),D=r.mul(j,ee),D=r.add(D,D),D=r.add(D,D),new C(M,H,D)}add(w){B(w);let{X:A,Y:x,Z:R}=this,{X:P,Y:N,Z:M}=w,H=r.ZERO,D=r.ZERO,q=r.ZERO,ee=i.a,j=r.mul(i.b,pr),V=r.mul(A,P),re=r.mul(x,N),ae=r.mul(R,M),ge=r.add(A,x),ne=r.add(P,N);ge=r.mul(ge,ne),ne=r.add(V,re),ge=r.sub(ge,ne),ne=r.add(A,R);let pe=r.add(P,M);return ne=r.mul(ne,pe),pe=r.add(V,ae),ne=r.sub(ne,pe),pe=r.add(x,R),H=r.add(N,M),pe=r.mul(pe,H),H=r.add(re,ae),pe=r.sub(pe,H),q=r.mul(ee,ne),H=r.mul(j,ae),q=r.add(H,q),H=r.sub(re,q),q=r.add(re,q),D=r.mul(H,q),re=r.add(V,V),re=r.add(re,V),ae=r.mul(ee,ae),ne=r.mul(j,ne),re=r.add(re,ae),ae=r.sub(V,ae),ae=r.mul(ee,ae),ne=r.add(ne,ae),V=r.mul(re,ne),D=r.add(D,V),V=r.mul(pe,ne),H=r.mul(ge,H),H=r.sub(H,V),V=r.mul(ge,re),q=r.mul(pe,q),q=r.add(q,V),new C(H,D,q)}subtract(w){return this.add(w.negate())}is0(){return this.equals(C.ZERO)}multiply(w){let{endo:A}=e;if(!s.isValidNot0(w))throw new Error("invalid scalar: out of range");let x,R,P=N=>O.cached(this,N,M=>an(C,M));if(A){let{k1neg:N,k1:M,k2neg:H,k2:D}=$(w),{p:q,f:ee}=P(M),{p:j,f:V}=P(D);R=ee.add(V),x=U(A.beta,q,j,N,H)}else{let{p:N,f:M}=P(w);x=N,R=M}return an(C,[x,R])[0]}multiplyUnsafe(w){let{endo:A}=e,x=this;if(!s.isValid(w))throw new Error("invalid scalar: out of range");if(w===Xe||x.is0())return C.ZERO;if(w===Mt)return x;if(O.hasCache(this))return this.multiply(w);if(A){let{k1neg:R,k1:P,k2neg:N,k2:M}=$(w),{p1:H,p2:D}=ks(C,x,P,M);return U(A.beta,H,D,R,N)}else return O.unsafe(x,w)}toAffine(w){return S(this,w)}isTorsionFree(){let{isTorsionFree:w}=e;return o===Mt?!0:w?w(C,this):O.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:w}=e;return o===Mt?this:w?w(C,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(w=!0){return Ut(w,"isCompressed"),this.assertValidity(),g(C,this,w)}toHex(w=!0){return De(this.toBytes(w))}toString(){return``}}let F=s.BITS,O=new ur(C,e.endo?Math.ceil(F/2):F);return C.BASE.precompute(8),C}function Ls(n){return Uint8Array.of(n?2:3)}function _s(n,e){return{secretKey:e.BYTES,publicKey:1+n.BYTES,publicKeyUncompressed:1+2*n.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function mo(n,e={}){let{Fn:t}=n,r=e.randomBytes||Ye,s=Object.assign(_s(n.Fp,t),{seed:rn(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:y}=s;try{let v=g.length;return f===!0&&v!==m||f===!1&&v!==y?!1:!!n.fromBytes(g)}catch{return!1}}function a(g=r(s.seed)){return hr(se(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:y}=s;if(!Dt(g)||"_lengths"in t&&t._lengths||f===m)return;let v=se(g,void 0,"key").length;return v===m||v===y}function h(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 y=t.fromBytes(g);return n.fromBytes(f).multiply(y).toBytes(m)}let u={isValidSecretKey:i,isValidPublicKey:o,randomSecretKey:a},p=dr(a,l);return Object.freeze({getPublicKey:l,getSharedSecret:h,keygen:p,Point:n,utils:u,lengths:s})}function Os(n,e,t={}){pt(e),Ft(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),t=Object.assign({},t);let r=t.randomBytes||Ye,s=t.hmac||((A,x)=>nt(e,A,x)),{Fp:i,Fn:o}=n,{ORDER:a,BITS:l}=o,{keygen:c,getPublicKey:h,getSharedSecret:u,utils:p,lengths:g}=mo(n,t),f={prehash:!0,lowS:typeof t.lowS=="boolean"?t.lowS:!0,format:"compact",extraEntropy:!1},m=a*Rs>Mt;return A>x}function v(A,x){if(!o.isValidNot0(x))throw new Error(`invalid signature ${A}: out of range 1..Point.Fn.ORDER`);return x}function b(){if(m)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function T(A,x){cn(x);let R=g.signature,P=x==="compact"?R:x==="recovered"?R+1:void 0;return se(A,P)}class B{r;s;recovery;constructor(x,R,P){if(this.r=v("r",x),this.s=v("s",R),P!=null){if(b(),![0,1,2,3].includes(P))throw new Error("invalid recovery id");this.recovery=P}Object.freeze(this)}static fromBytes(x,R=f.format){T(x,R);let P;if(R==="der"){let{r:D,s:q}=st.toSig(se(x));return new B(D,q)}R==="recovered"&&(P=x[0],R="compact",x=x.subarray(1));let N=g.signature/2,M=x.subarray(0,N),H=x.subarray(N,N*2);return new B(o.fromBytes(M),o.fromBytes(H),P)}static fromHex(x,R){return this.fromBytes(Oe(x),R)}assertRecovery(){let{recovery:x}=this;if(x==null)throw new Error("invalid recovery id: must be present");return x}addRecoveryBit(x){return new B(this.r,this.s,x)}recoverPublicKey(x){let{r:R,s:P}=this,N=this.assertRecovery(),M=N===2||N===3?R+a:R;if(!i.isValid(M))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let H=i.toBytes(M),D=n.fromBytes(Se(Ls((N&1)===0),H)),q=o.inv(M),ee=S(se(x,void 0,"msgHash")),j=o.create(-ee*q),V=o.create(P*q),re=n.BASE.multiplyUnsafe(j).add(D.multiplyUnsafe(V));if(re.is0())throw new Error("invalid recovery: point at infinify");return re.assertValidity(),re}hasHighS(){return y(this.s)}toBytes(x=f.format){if(cn(x),x==="der")return Oe(st.hexFromSig(this));let{r:R,s:P}=this,N=o.toBytes(R),M=o.toBytes(P);return x==="recovered"?(b(),Se(Uint8Array.of(this.assertRecovery()),N,M)):Se(N,M)}toHex(x){return De(this.toBytes(x))}}let $=t.bits2int||function(x){if(x.length>8192)throw new Error("input is too large");let R=rt(x),P=x.length*8-l;return P>0?R>>BigInt(P):R},S=t.bits2int_modN||function(x){return o.create($(x))},L=qt(l);function U(A){return ls("num < 2^"+l,A,Xe,L),o.toBytes(A)}function C(A,x){return se(A,void 0,"message"),x?se(e(A),void 0,"prehashed message"):A}function F(A,x,R){let{lowS:P,prehash:N,extraEntropy:M}=ln(R,f);A=C(A,N);let H=S(A),D=o.fromBytes(x);if(!o.isValidNot0(D))throw new Error("invalid private key");let q=[U(D),U(H)];if(M!=null&&M!==!1){let re=M===!0?r(g.secretKey):M;q.push(se(re,void 0,"extraEntropy"))}let ee=Se(...q),j=H;function V(re){let ae=$(re);if(!o.isValidNot0(ae))return;let ge=o.inv(ae),ne=n.BASE.multiply(ae).toAffine(),pe=o.create(ne.x);if(pe===Xe)return;let Q=o.create(ge*o.create(j+pe*D));if(Q===Xe)return;let me=(ne.x===pe?0:2)|Number(ne.y&Mt),et=Q;return P&&y(Q)&&(et=o.neg(Q),me^=1),new B(pe,et,m?void 0:me)}return{seed:ee,k2sig:V}}function O(A,x,R={}){let{seed:P,k2sig:N}=F(A,x,R);return cs(e.outputLen,o.BYTES,s)(P,N).toBytes(R.format)}function d(A,x,R,P={}){let{lowS:N,prehash:M,format:H}=ln(P,f);if(R=se(R,void 0,"publicKey"),x=C(x,M),!Dt(A)){let D=A instanceof B?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+D)}T(A,H);try{let D=B.fromBytes(A,H),q=n.fromBytes(R);if(N&&D.hasHighS())return!1;let{r:ee,s:j}=D,V=S(x),re=o.inv(j),ae=o.create(V*re),ge=o.create(ee*re),ne=n.BASE.multiplyUnsafe(ae).add(q.multiplyUnsafe(ge));return ne.is0()?!1:o.create(ne.x)===ee}catch{return!1}}function w(A,x,R={}){let{prehash:P}=ln(R,f);return x=C(x,P),B.fromBytes(A,"recovered").recoverPublicKey(x).toBytes()}return Object.freeze({keygen:c,getPublicKey:h,getSharedSecret:u,utils:p,lengths:g,Point:n,sign:O,verify:d,recoverPublicKey:w,Signature:B,hash:e})}var yr={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},yo={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},bo=BigInt(0),un=BigInt(2);function wo(n){let e=yr.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,h=c*c*n%e,u=Ne(h,t,e)*h%e,p=Ne(u,t,e)*h%e,g=Ne(p,un,e)*c%e,f=Ne(g,s,e)*g%e,m=Ne(f,i,e)*f%e,y=Ne(m,a,e)*m%e,v=Ne(y,l,e)*y%e,b=Ne(v,a,e)*m%e,T=Ne(b,t,e)*h%e,B=Ne(T,o,e)*f%e,$=Ne(B,r,e)*c%e,S=Ne($,un,e);if(!gr.eql(gr.sqr(S),n))throw new Error("Cannot find square root");return S}var gr=At(yr.p,{sqrt:wo}),yt=Ts(yr,{Fp:gr,endo:yo}),Ns=Os(yt,Fe),Is={};function mr(n,...e){let t=Is[n];if(t===void 0){let r=Fe(as(n));t=Se(r,r),Is[n]=t}return Fe(Se(t,...e))}var fn=n=>n.toBytes(!0).slice(1),pn=n=>n%un===bo;function dn(n){let{Fn:e,BASE:t}=yt,r=e.fromBytes(n),s=t.multiply(r);return{scalar:pn(s.y)?r:e.neg(r),bytes:fn(s)}}function Ps(n){let e=gr;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);pn(s)||(s=e.neg(s));let i=yt.fromAffine({x:n,y:s});return i.assertValidity(),i}var Wt=rt;function Hs(...n){return yt.Fn.create(Wt(mr("BIP0340/challenge",...n)))}function Cs(n){return dn(n).bytes}function vo(n,e,t=Ye(32)){let{Fn:r}=yt,s=se(n,void 0,"message"),{bytes:i,scalar:o}=dn(e),a=se(t,32,"auxRand"),l=r.toBytes(o^Wt(mr("BIP0340/aux",a))),c=mr("BIP0340/nonce",l,i,s),{bytes:h,scalar:u}=dn(c),p=Hs(h,i,s),g=new Uint8Array(64);if(g.set(h,0),g.set(r.toBytes(r.create(u+p*o)),32),!Ds(g,s,i))throw new Error("sign: Invalid signature produced");return g}function Ds(n,e,t){let{Fp:r,Fn:s,BASE:i}=yt,o=se(n,64,"signature"),a=se(e,void 0,"message"),l=se(t,32,"publicKey");try{let c=Ps(Wt(l)),h=Wt(o.subarray(0,32));if(!r.isValidNot0(h))return!1;let u=Wt(o.subarray(32,64));if(!s.isValidNot0(u))return!1;let p=Hs(s.toBytes(h),fn(c),a),g=i.multiplyUnsafe(u).add(c.multiplyUnsafe(s.neg(p))),{x:f,y:m}=g.toAffine();return!(g.is0()||!pn(m)||f!==h)}catch{return!1}}var Bt=(()=>{let t=(r=Ye(48))=>hr(r,yr.n);return{keygen:dr(t,Cs),getPublicKey:Cs,sign:vo,verify:Ds,Point:yt,utils:{randomSecretKey:t,taggedHash:mr,lift_x:Ps,pointToBytes:fn},lengths:{secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:64,seed:48}}})();var tc=new TextDecoder("utf-8"),xo=new TextEncoder;function So(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 Rt=Symbol("verified"),Eo=n=>n instanceof Object;function Ao(n){if(!Eo(n)||typeof n.kind!="number"||typeof n.content!="string"||typeof n.created_at!="number"||typeof n.pubkey!="string"||!So(n.pubkey)||!Array.isArray(n.tags))return!1;for(let e=0;e{function t(r,...s){if(Ee(r,void 0,"key"),!To)throw new Error("Non little-endian hardware is not yet supported");if(n.nonceLength!==void 0){let h=s[0];Ee(h,n.varSizeNonce?void 0:n.nonceLength,"nonce")}let i=n.tagLength;i&&s[1]!==void 0&&Ee(s[1],void 0,"AAD");let o=e(r,...s),a=(h,u)=>{if(u!==void 0){if(h!==2)throw new Error("cipher output not supported");Ee(u,void 0,"output")}},l=!1;return{encrypt(h,u){if(l)throw new Error("cannot encrypt() twice with same key + nonce");return l=!0,Ee(h),a(o.encrypt.length,u),o.encrypt(h,u)},decrypt(h,u){if(Ee(h),i&&h.lengthUint8Array.from(n.split(""),e=>e.charCodeAt(0)),_o=Ws("expand 16-byte k"),Oo=Ws("expand 32-byte k"),Io=Je(_o),Co=Je(Oo);function Y(n,e){return n<>>32-e}function bn(n){return n.byteOffset%4===0}var Er=64,No=16,Ks=2**32-1,js=Uint32Array.of();function Po(n,e,t,r,s,i,o,a){let l=s.length,c=new Uint8Array(Er),h=Je(c),u=bn(s)&&bn(i),p=u?Je(s):js,g=u?Je(i):js;for(let f=0;f=Ks)throw new Error("arx: counter overflow");let m=Math.min(Er,l-f);if(u&&m===Er){let y=f/4;if(f%4!==0)throw new Error("arx: invalid block position");for(let v=0,b;v{Ee(a,void 0,"key"),Ee(l,void 0,"nonce"),Ee(c,void 0,"data");let p=c.length;if(h===void 0&&(h=new Uint8Array(p)),Ee(h,void 0,"output"),xr(u),u<0||u>=Ks)throw new Error("arx: counter overflow");if(h.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 h=0;h<8;h++)this.pad[h]=ke(e,16+2*h)}process(e,t,r=!1){let s=r?0:2048,{h:i,r:o}=this,a=o[0],l=o[1],c=o[2],h=o[3],u=o[4],p=o[5],g=o[6],f=o[7],m=o[8],y=o[9],v=ke(e,t+0),b=ke(e,t+2),T=ke(e,t+4),B=ke(e,t+6),$=ke(e,t+8),S=ke(e,t+10),L=ke(e,t+12),U=ke(e,t+14),C=i[0]+(v&8191),F=i[1]+((v>>>13|b<<3)&8191),O=i[2]+((b>>>10|T<<6)&8191),d=i[3]+((T>>>7|B<<9)&8191),w=i[4]+((B>>>4|$<<12)&8191),A=i[5]+($>>>1&8191),x=i[6]+(($>>>14|S<<2)&8191),R=i[7]+((S>>>11|L<<5)&8191),P=i[8]+((L>>>8|U<<8)&8191),N=i[9]+(U>>>5|s),M=0,H=M+C*a+F*(5*y)+O*(5*m)+d*(5*f)+w*(5*g);M=H>>>13,H&=8191,H+=A*(5*p)+x*(5*u)+R*(5*h)+P*(5*c)+N*(5*l),M+=H>>>13,H&=8191;let D=M+C*l+F*a+O*(5*y)+d*(5*m)+w*(5*f);M=D>>>13,D&=8191,D+=A*(5*g)+x*(5*p)+R*(5*u)+P*(5*h)+N*(5*c),M+=D>>>13,D&=8191;let q=M+C*c+F*l+O*a+d*(5*y)+w*(5*m);M=q>>>13,q&=8191,q+=A*(5*f)+x*(5*g)+R*(5*p)+P*(5*u)+N*(5*h),M+=q>>>13,q&=8191;let ee=M+C*h+F*c+O*l+d*a+w*(5*y);M=ee>>>13,ee&=8191,ee+=A*(5*m)+x*(5*f)+R*(5*g)+P*(5*p)+N*(5*u),M+=ee>>>13,ee&=8191;let j=M+C*u+F*h+O*c+d*l+w*a;M=j>>>13,j&=8191,j+=A*(5*y)+x*(5*m)+R*(5*f)+P*(5*g)+N*(5*p),M+=j>>>13,j&=8191;let V=M+C*p+F*u+O*h+d*c+w*l;M=V>>>13,V&=8191,V+=A*a+x*(5*y)+R*(5*m)+P*(5*f)+N*(5*g),M+=V>>>13,V&=8191;let re=M+C*g+F*p+O*u+d*h+w*c;M=re>>>13,re&=8191,re+=A*l+x*a+R*(5*y)+P*(5*m)+N*(5*f),M+=re>>>13,re&=8191;let ae=M+C*f+F*g+O*p+d*u+w*h;M=ae>>>13,ae&=8191,ae+=A*c+x*l+R*a+P*(5*y)+N*(5*m),M+=ae>>>13,ae&=8191;let ge=M+C*m+F*f+O*g+d*p+w*u;M=ge>>>13,ge&=8191,ge+=A*h+x*c+R*l+P*a+N*(5*y),M+=ge>>>13,ge&=8191;let ne=M+C*y+F*m+O*f+d*g+w*p;M=ne>>>13,ne&=8191,ne+=A*u+x*h+R*c+P*l+N*a,M+=ne>>>13,ne&=8191,M=(M<<2)+M|0,M=M+H|0,H=M&8191,M=M>>>13,D+=M,i[0]=H,i[1]=D,i[2]=q,i[3]=ee,i[4]=j,i[5]=V,i[6]=re,i[7]=ae,i[8]=ge,i[9]=ne}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){gn(this),Ee(e),e=Tt(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 Ho(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 Vs=Ho(n=>new vn(n));function Ys(n,e,t,r,s,i=20){let o=n[0],a=n[1],l=n[2],c=n[3],h=e[0],u=e[1],p=e[2],g=e[3],f=e[4],m=e[5],y=e[6],v=e[7],b=s,T=t[0],B=t[1],$=t[2],S=o,L=a,U=l,C=c,F=h,O=u,d=p,w=g,A=f,x=m,R=y,P=v,N=b,M=T,H=B,D=$;for(let ee=0;ee{n.update(e);let t=e.length%16;t&&n.update(zo.subarray(t))},qo=new Uint8Array(32);function Gs(n,e,t,r,s){s!==void 0&&Ee(s,void 0,"AAD");let i=n(e,t,qo),o=Fs(r.length,s?s.length:0,!0),a=Vs.create(i);s&&$s(a,s),$s(a,r),a.update(o);let l=a.digest();return Qe(i,o),l}var Zs=n=>(e,t,r)=>({encrypt(i,o){let a=i.length;o=yn(a+16,o,!1),o.set(i);let l=o.subarray(0,-16);n(e,t,l,l,1);let c=Gs(n,e,t,l,r);return o.set(c,a),Qe(c),o},decrypt(i,o){o=yn(i.length-16,o,!1);let a=i.subarray(0,-16),l=i.subarray(-16),c=Gs(n,e,t,a,r);if(!Sr(l,c))throw new Error("invalid tag");return o.set(i.subarray(0,-16)),n(e,t,o,o,1),Qe(c),o}}),wc=mn({blockSize:64,nonceLength:12,tagLength:16},Zs(Ar)),vc=mn({blockSize:64,nonceLength:24,tagLength:16},Zs(Uo));function Js(n,e,t){return pt(n),t===void 0&&(t=new Uint8Array(n.outputLen)),nt(n,t,e)}var xn=Uint8Array.of(0),Xs=Uint8Array.of();function Qs(n,e,t,r=32){pt(n),He(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=Xs:se(t,void 0,"info");let o=new Uint8Array(i*s),a=nt.create(n,e),l=a._cloneInto(),c=new Uint8Array(a.outputLen);for(let h=0;htypeof t=="string"):e.every(t=>Number.isSafeInteger(t)):!1}function Gt(n,e){if(typeof e!="string")throw new Error(`${n}: string expected`);return!0}function An(n){if(!Number.isSafeInteger(n))throw new Error(`invalid integer: ${n}`)}function En(n){if(!Array.isArray(n))throw new Error("array expected")}function kr(n,e){if(!ri(!0,e))throw new Error(`${n}: array of strings expected`)}function jo(n,e){if(!ri(!1,e))throw new Error(`${n}: array of numbers expected`)}function Wo(...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 Ko(n){let e=typeof n=="string"?n.split(""):n,t=e.length;kr("alphabet",e);let r=new Map(e.map((s,i)=>[s,i]));return{encode:s=>(En(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=>(En(s),s.map(i=>{Gt("alphabet.decode",i);let o=r.get(i);if(o===void 0)throw new Error(`Unknown letter: "${i}". Allowed: ${n}`);return o}))}}function Vo(n=""){return Gt("join",n),{encode:e=>(kr("join.decode",e),e.join(n)),decode:e=>(Gt("join.decode",e),e.split(n))}}function $o(n,e="="){return An(n),Gt("padding",e),{encode(t){for(kr("padding.encode",t);t.length*n%8;)t.push(e);return t},decode(t){kr("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 ni=(n,e)=>e===0?n:ni(e,n%e),Mr=(n,e)=>n+(e-ni(n,e)),Sn=(()=>{let n=[];for(let e=0;e<40;e++)n.push(2**e);return n})();function ei(n,e,t,r){if(En(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(Mr(e,t)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${t} carryBits=${Mr(e,t)}`);let s=0,i=0,o=Sn[e],a=Sn[t]-1,l=[];for(let c of n){if(An(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 h=Sn[i];if(h===void 0)throw new Error("invalid carry");s&=h-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 Go(n,e=!1){if(An(n),n<=0||n>32)throw new Error("radix2: bits should be in (0..32]");if(Mr(8,n)>32||Mr(n,8)>32)throw new Error("radix2: carry overflow");return{encode:t=>{if(!ti(t))throw new Error("radix2.encode input should be Uint8Array");return ei(Array.from(t),8,n,!e)},decode:t=>(jo("radix2.decode",t),Uint8Array.from(ei(t,n,8,e)))}}var Yo=typeof Uint8Array.from([]).toBase64=="function"&&typeof Uint8Array.fromBase64=="function",Zo=(n,e)=>{Gt("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"})},kn=Yo?{encode(n){return Fo(n),n.toBase64()},decode(n){return Zo(n,!1)}}:Wo(Go(6),Ko("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),$o(6),Vo(""));var Xo=new TextDecoder("utf-8"),si=new TextEncoder,Mn=1,Bn=4294967295,Rn=65536;function Jo(n,e){let t=Ns.getSharedSecret(n,Oe("02"+e)).subarray(1,33);return Js(Fe,t,si.encode("nip44-v2"))}function ii(n,e){let t=Qs(Fe,n,e,76);return{chacha_key:t.subarray(0,32),chacha_nonce:t.subarray(32,44),hmac_key:t.subarray(44,76)}}function Tn(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 Qo(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 ea(n){if(!Number.isSafeInteger(n)||nBn)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 oi(n){let e=si.encode(n),t=e.length;if(tBn)throw new Error("invalid plaintext size: must be between 1 and 4294967295 bytes");let r=t>=Rn?Se(new Uint8Array([0,0]),ea(t)):Qo(t),s=new Uint8Array(Tn(t)-t);return Se(r,e,s)}function ai(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),rBn||i.length!==r||n.length!==s+Tn(r))throw new Error("invalid padding");return Xo.decode(i)}function li(n,e,t){if(t.length!==32)throw new Error("AAD associated data must be 32 bytes");let r=Se(t,e);return nt(Fe,n,r)}function ta(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=kn.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 ra(n,e,t=Ye(32)){let{chacha_key:r,chacha_nonce:s,hmac_key:i}=ii(e,t),o=oi(n),a=Ar(r,s,o),l=li(i,a,t);return kn.encode(Se(new Uint8Array([2]),t,a,l))}function na(n,e){let{nonce:t,ciphertext:r,mac:s}=ta(n),{chacha_key:i,chacha_nonce:o,hmac_key:a}=ii(e,t),l=li(a,r,t);if(!Sr(l,s))throw new Error("invalid MAC");let c=Ar(i,o,r);return ai(c)}var Br={utils:{getConversationKey:Jo,calcPaddedLen:Tn,pad:oi,unpad:ai},encrypt:ra,decrypt:na};function Yt(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 Rr=3,Tr=24170,Ln=24171,Lr="x",Zt=/^[0-9a-f]{64}$/u,sa=/^[a-z0-9](?:[a-z0-9-]{0,31})$/u,ia=1*1024*1024,ci=16*1024,oa=64*1024,hi=8*1024,aa=2*1024,ui=30,la=64,ca=256,di=new TextEncoder;function bt(n){return typeof n=="string"?di.encode(n).byteLength:n instanceof ArrayBuffer||ArrayBuffer.isView(n)?n.byteLength:di.encode(String(n)).byteLength}function ha(n){return Array.from(globalThis.crypto.getRandomValues(new Uint8Array(n)),e=>e.toString(16).padStart(2,"0")).join("")}function yi(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 _n=n=>Math.min(Number.MAX_SAFE_INTEGER,n);function fi(n,e){let t=yi(n,e);return t.length===1?t[0]:null}function pi(n){let e=JSON.parse(n);if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Expected a JSON object.");return e}function it(n){return typeof n=="string"&&sa.test(n)}function gi(n){return typeof n=="string"&&n.length>=8&&n.length<=64&&/^[a-zA-Z0-9_-]+$/u.test(n)}function ua(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 _r=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(ua))],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.#n().finally(()=>{this.connecting=null}),this.connecting)}async#n(){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,h]of this.subscriptions)i.send(JSON.stringify(["REQ",c,h]));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)>ia)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&&!Yt(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=ha(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()}},Or=class{#n=null;#t=null;#e=new Map;#s=null;constructor({pool:e,swarmId:t,secretKey:r=Vt(),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=Us(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={[`#${Lr}`]:[this.swarmId],since:Math.floor(Date.now()/1e3)-2};try{this.#t=this.pool.onRelayOpen?.(t=>{if(!this.started||!this.#n)return;let r=Math.floor(Date.now()/1e3)-this.#n.created_at;if(!Number.isFinite(r)||!Number.isFinite(this.maxEventAgeSeconds)||r<-ui||r>this.maxEventAgeSeconds){this.#n=null;return}t(this.#n)}),this.subscriptionId=this.pool.subscribe({...e,since:Math.floor(Date.now()/1e3)-this.maxEventAgeSeconds,kinds:[Tr]}),this.subscriptionIds.push(this.subscriptionId),this.subscriptionIds.push(this.pool.subscribe({...e,kinds:[Ln],"#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.#n=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&&!we(i))throw new Error("Invalid presence ticket.");if(!it(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=>!Zt.test(c)))throw new Error("Invalid object hash list.");let o=t.map(c=>{if(!c||typeof c!="object"||!it(c.type)||!Zt.test(c.publicKey)||c.obj!==void 0&&!mi(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:Rr,role:e,transports:o,have:[...new Set(r)],...s===void 0?{}:{open:!!s},...i===void 0?{}:{ticket:i}});if(bt(a)>ci)throw new Error("Presence payload is too large.");let l=wr({kind:Tr,created_at:Math.floor(Date.now()/1e3),tags:[[Lr,this.swarmId]],content:a},this.secretKey);return this.pool.publish(l),this.#n=JSON.parse(JSON.stringify(l)),l}sendSignal(e,{type:t,transport:r,requestId:s,payload:i={}}={}){if(!Zt.test(e))throw new Error("Invalid signal recipient.");if(!it(t)||!it(r)||!gi(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:Rr,type:t,transport:r,requestId:s,payload:i});if(bt(o)>hi)throw new Error("Signal payload is too large.");let a=Br.encrypt(o,this.#r(e)),l=wr({kind:Ln,created_at:Math.floor(Date.now()/1e3),tags:[[Lr,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 h=!1;try{h=t(c)}catch(u){clearTimeout(l),e.delete(a),o(u);return}h&&(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!==Tr&&e.kind!==Ln||!Number.isSafeInteger(e.created_at)||fi(e,Lr)!==this.swarmId)return;let t=Math.floor(Date.now()/1e3)-e.created_at;if(t<-ui){this.clock.aheadRejected=_n(this.clock.aheadRejected+1),this.clock.maxAheadSeconds=Math.max(this.clock.maxAheadSeconds,_n(-t));return}if(t>this.maxEventAgeSeconds){this.clock.staleRejected=_n(this.clock.staleRejected+1);return}try{e.kind===Tr?this.#c(e):this.#o(e)}catch{}}#c(e){if(bt(e.content)>ci||yi(e,"p").length!==0)return;let t=pi(e.content);if(t.v!==Rr||!it(t.role)||!Array.isArray(t.transports)||t.transports.length>8||!Array.isArray(t.have)||t.have.length>32||t.have.some(o=>!Zt.test(o)))return;let r=t.transports.map(o=>{if(!o||typeof o!="object"||!it(o.type)||!Zt.test(o.publicKey))throw new Error("Invalid transport capability.");return{type:o.type,publicKey:o.publicKey,...mi(o.obj)?{obj:o.obj}:{}}}),s=typeof t.open=="boolean"?t.open:null,i=we(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)>oa||fi(e,"p")!==this.pubkey)return;let t=Br.decrypt(e.content,this.#r(e.pubkey));if(bt(t)>hi)return;let r=pi(t);r.v!==Rr||!it(r.type)||!it(r.transport)||!gi(r.requestId)||!r.payload||typeof r.payload!="object"||Array.isArray(r.payload)||(this.clock.signalAges.length>=la&&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}))}#r(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=Br.utils.getConversationKey(this.secretKey,e),this.#e.size>=ca&&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.#n=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 mi(n){return Number.isSafeInteger(n)&&n>=1&&n<=15}function we(n){return typeof n=="string"&&n.length>0&&bt(n)<=aa}var On=/^[0-9a-f]{64}$/u,bi="relayswarm-abandon";var wi=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"]),ot=class{static ABANDON_REASON=bi;#n=!1;constructor({pubkey:e,pc:t,channel:r,maxSegmentBytes:s,onRequest:i,onHaveChange:o,onScheduleChange:a,onClose:l,onUploadCancelled:c,maxQueuedRequests:h=4,drainTimeoutMs:u=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=h,this.drainTimeoutMs=u,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=(h,u=null)=>{if(!l&&(l=!0,typeof i=="function"))try{let p=null;if(Number.isFinite(a))try{p=performance.now()-a}catch{}let g=u?.received??0,f=Number.isFinite(u?.firstByteAt)&&Number.isFinite(a)?u.firstByteAt-a:null;i({outcome:h,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:u?u.size>=0:!1,draining:u?.draining===!0,closeReason:wi.has(this.closeReason)?this.closeReason:null})}catch{}};if(this.closed||this.pending||r?.aborted){let h=Promise.resolve(null);return c(this.closed?"closed":this.pending?"busy":"abort"),h}return new Promise(h=>{let u=this.nextId++,p=b=>{clearTimeout(this.pending.timer),r?.removeEventListener("abort",m),h(b)},g=(b,T=b?"payload":"none",B=!0)=>{if(this.pending?.id!==u)return;let $=this.pending,S=$.draining;p(b),this.pending=null,b&&(this.lastDeliveredAt=Date.now()),S&&!this.closed&&this.onScheduleChange?.(this),B&&c(T,$)},f=b=>{let T=this.pending;if(!T||T.id!==u||T.draining)return;let B=!1;try{B=this.channel.ordered===!0&&this.channel.maxRetransmits===null&&this.channel.maxPacketLifeTime===null&&this.channel.readyState==="open"}catch{}let $=b!=="request-abort"?"timeout":r?.reason===bi?"abandoned":"abort";if(!B){g(null,$,!1);try{this.close(b)}finally{c($,T)}return}T.draining=!0,T.parts.length=0,p(null),T.timer=setTimeout(()=>{this.pending===T&&T.draining&&this.close(b)},this.drainTimeoutMs),c($,T),T.cancelled=this.#t({t:"cancel",id:u})},m=()=>f("request-abort"),y=()=>f("request-timeout"),v=typeof o=="function"?b=>{try{o(b.received,b.size,Number.isFinite(a)?b.firstByteAt-a:null)}catch{}}:null;this.pending={id:u,key:e,expectedSize:s,size:-1,parts:[],chunks:0,received:0,firstByteAt:null,progress:v,draining:!1,cancelled:!1,finish:g,timer:setTimeout(y,Math.max(1,t))},r?.addEventListener("abort",m,{once:!0}),this.#t({t:"want",id:u,k:e})||g(null,"send-error")})}close(e="host"){if(!this.closed){this.closed=!0,this.closeReason=wi.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"&&On.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"||!On.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.#n?"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.#n=!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 vi(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 da=n=>vi(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 da(this.recentFirstBytes)}rate(){let e=this.firstByteMs(),t=e===null?[]:this.recentRates.filter(({flowMs:r})=>r>=e*3);return vi((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),h=a.length&&(!c.length||this.turn===0&&i>=100);this.turn=(this.turn+1)%4;let u=h?a:c.length?c:l,p=f=>{let m=this.summary(f);return h?m.lastSelected:(this.estimate(f,s)??1e3)*(1+m.failureRate*4)},g=u.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 Xt=/^[0-9a-f]{64}$/u,fa=4,pa=1e4,ga=8,xi=2e4,Lt=class{constructor(e=()=>Date.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||!Xt.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){!Xt.test(e)||!Array.isArray(t)||(this.candidates.delete(e),this.candidates.set(e,{pubkey:e,have:[...new Set(t.filter(s=>typeof s=="string"&&Xt.test(s)))].slice(-8),ticket:we(r)?r:null,at:this.clock()}),this.candidates.size>64&&this.candidates.delete(this.candidates.keys().next().value))}#n(e){return!!(e&&this.contexts.get(e.mediaType)===e)}holderMiss(e,t,r){if(!this.#n(e)||!Xt.test(t)||!Xt.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>=ga&&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.#n(e)&&e.holders.delete(t)}stale(e,t){let r=this.#n(e)?e.holders.get(t):null;return!!r&&r.misses>=fa&&this.clock()-r.firstMissAt>=pa}forget(e){for(let t of this.contexts.values())t.holders.delete(e)}spent(e){return e.spentAt!==null}rearm(e,t){if(!this.#n(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:xi,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 at(n,e,t){return new Promise((r,s)=>{let i=new AbortController,o=!1,a,l=(h,u,p=!1,g=u)=>{o||(o=!0,clearTimeout(a),e?.removeEventListener("abort",c),p&&i.abort(g),h?r(u):s(u))},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(h=>l(!0,h),h=>l(!1,h))})}var Si=24172,ma=24173,ya=24174,In=/^[0-9a-f]{64}$/u,ba="relayswarm-segment-v1",wa="relayswarm-segment-v2",va="relayswarm-segment-v3",Ei={1:ba,2:wa,3:va},xa=new TextEncoder,Sa=512,vt=new Map;function Ir(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=Kt(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):$t(e)?(vt.size>=Sa&&vt.delete(vt.keys().next().value),vt.set(r,!0),!0):!1}function Cr(n){return xa.encode(JSON.stringify(n)).length<=16*1024}function lt(n,e){let t=n.tags.filter(r=>r[0]===e);return t.length===1&&t[0].length===2?t[0][1]:null}function Cn(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 Ai(n){return n.v===3?3:n.v===2?2:1}function ki(n){let e=Ai(n),t=e>=2;return JSON.stringify({domain:Ei[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 Ea(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 Aa(n){return JSON.stringify({domain:"relayswarm-commitment-revocation-v1",v:1,streamEventId:n.streamEventId,swarmId:n.swarmId,delegationId:n.delegationId})}function Nr(n){try{return n.kind===30311&&Cr(n)&&Ir(n)&&typeof lt(n,"d")=="string"&&n.tags.some(e=>e.length===3&&e[0]==="relayswarm"&&e[1]==="redistribute"&&e[2]==="1")}catch{return!1}}function ka(n,{streamEvent:e,swarmId:t,revokedDelegationIds:r=[],delegationRevocations:s=[]},i=Date.now()){try{let o=Math.floor(i/1e3);if(!Nr(e)||!n||!Cr(n)||n.kind!==ma||n.pubkey!==e.pubkey||!Ir(n)||lt(n,"x")!==t||lt(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!==Ea(a)||a.domain!=="relayswarm-commitment-delegation-v1"||a.v!==1||a.streamEventId!==e.id||a.swarmId!==t||!In.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=>!(Cn(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||!Cr(l)||l.kind!==ya||l.pubkey!==e.pubkey||!Number.isSafeInteger(l.created_at)||l.created_ato+30||!Ir(l)||lt(l,"e")!==n.id||lt(l,"x")!==t)continue;let c=JSON.parse(l.content);if(l.content===Aa(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 _t(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))||!Cn(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||!Cn(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 Mi(n,{streamEvent:e,swarmId:t,key:r,context:s,maxSegmentBytes:i,delegation:o,revokedDelegationIds:a,delegationRevocations:l},c=Date.now()){try{let h=Math.floor(c/1e3);if(!Number.isSafeInteger(i)||i<1||i>16*1024*1024||!Nr(e)||!n||n.kind!==Si||!Cr(n)||!Number.isSafeInteger(n.created_at)||n.created_at>h+30||n.created_at=2;if(n.content!==ki(u)||u.domain!==Ei[p]||![1,2,3].includes(u.v)||u.streamEventId!==e.id||u.swarmId!==t||u.key!==r||u.sequence!==s.frag.sn||u.discontinuity!==(s.frag.cc??0)||u.part!==(s.part?.index??null)||!Number.isSafeInteger(u.sequence)||u.sequence<0||!Number.isSafeInteger(u.discontinuity)||u.discontinuity<0||u.part!==null&&(!Number.isSafeInteger(u.part)||u.part<0)||!In.test(u.sha256)||!Number.isSafeInteger(u.size)||u.size<1||u.size>i||!Number.isSafeInteger(u.expiresAt)||u.expiresAt<=h||u.expiresAt>h+300||p===3&&(u.pieceSize!==xt(u.size)||!Array.isArray(u.pieces)||u.pieces.length!==Math.ceil(u.size/u.pieceSize)||u.pieces.some(f=>typeof f!="string"||!In.test(f))))return null;if(g){let f=_t(s);if(!f||u.rendition!==f.playlist||u.playlist!==f.playlist||u.mediaType!==f.mediaType||JSON.stringify(u.encryption)!==JSON.stringify(f.encryption))return null}else if(u.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=ka(o,{streamEvent:e,swarmId:t,revokedDelegationIds:a,delegationRevocations:l},c);if(!f||n.pubkey!==f.delegatePubkey||lt(n,"delegation")!==o.id||n.created_atf.expiresAt||!f.renditions.includes(u.rendition)||!f.mediaTypes.includes(g?u.mediaType:"main")||u.part!==null&&!f.allowParts||u.size>f.maxSegmentBytes)return null}return u}catch{return null}}var Bi=new TextEncoder,Ma=new TextDecoder;function Ri(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 Ba=(n,e)=>new Uint8Array(n.memory.buffer,n.rs_result_ptr(),e);function Ti(n,{size:e,sha256:t,pieces:r,deadline:s,maxHolders:i,originReserveMs:o,peerOnly:a=!1},l,c){if(l()||!Ra.every(h=>typeof n[h]=="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 h=Ri(n,Bi.encode(JSON.stringify({sha256:t,pieces:r,...a?{peerOnly:!0}:{}})),(u,p)=>n.rs_xfer_new(e,s,i,o,u,p));return h?new Pn(n,h,l,c,a):null}catch(h){return c(h),null}}var Ra=["rs_xfer_new","rs_xfer_call","rs_xfer_free"],Jt={start:0,delivered:1,failed:2,tick:3,state:4,progress:5},Pn=class{#n;#t;#e;#s;#d;constructor(e,t,r,s,i=!1){this.#n=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.#n.rs_xfer_capabilities=="function"&&!!(this.#n.rs_xfer_capabilities()&1)}catch{}let l=new Set(o),c=a?t:t.filter(([h])=>!l.has(h));return this.#i(Jt.start,e,-1,0,0,Bi.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(Jt.delivered,e,t,r.start,r.end,s)}failed(e,t){return this.#i(Jt.failed,e,t,0,0,Nn)}tick(e){return this.#i(Jt.tick,e,-1,0,0,Nn)}progress(e,t,r){return this.#i(Jt.progress,e,t,r,0,Nn)}free(){if(this.#t===null)return;let e=this.#t;if(this.#t=null,!this.#e())try{this.#n.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.#n;try{let l=Ri(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=Ba(a,l),h=new DataView(c.buffer,c.byteOffset,l).getUint32(0,!0),u=JSON.parse(Ma.decode(c.subarray(4,4+h))),p=l>4+h?c.slice(4+h):null;return{commands:u.c.map(f=>f.p?{...f,range:{start:f.p[0],end:f.p[1]}}:f),next:u.next,late:u.late,finished:u.finished,verified:u.verified??null,bytes:p}}catch(l){return this.#s(l),null}}},Nn=new Uint8Array(0);var Me={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},Ue={sendText:1,sendBinary:2,closed:3,report:4,resolved:5,haveChanged:6,scheduleChanged:7,serveRequest:8,uploadCancelled:9,progress:10,serveRange:11},Ta=128*1024,La=32*1024,_a=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"]),ct=new TextEncoder,Ot=new TextDecoder,Hn=new Uint8Array(0),Dn=()=>{try{return globalThis.performance.now()}catch{return null}},Li=n=>{let e=Math.trunc(Math.max(1,n));return e>=1&&e<=2**31-1?e:1},Pr=class n{get supportsRanges(){return!this.closed}static ABANDON_REASON=ot.ABANDON_REASON;#n;#t;#e=-1;#s=null;#d=null;#i=0;#c=!1;#o=!1;#r=new Map;#h=null;#k=!1;#M=0;constructor({pubkey:e,pc:t,channel:r,maxSegmentBytes:s,onRequest:i,onHaveChange:o,onScheduleChange:a,onClose:l,onUploadCancelled:c,maxQueuedRequests:h=4,drainTimeoutMs:u=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=h,this.drainTimeoutMs=u,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.#n=p,this.#i=this.openedAt,this.#t=p.newLink(s,h,u,this.#l(),this.openedAt),p.links.add(this),r.binaryType="arraybuffer",r.bufferedAmountLowThreshold=La,r.addEventListener("message",g=>{if(this.closed)return;let{data:f}=g;typeof f=="string"?this.#a(Me.text,{bytes:ct.encode(f)}):this.#a(Me.binary,{bytes:f instanceof ArrayBuffer?new Uint8Array(f):ArrayBuffer.isView(f)?new Uint8Array(f.buffer,f.byteOffset,f.byteLength):Hn})}),r.addEventListener("close",()=>this.close("channel-close")),r.addEventListener("error",()=>this.close("channel-error")),r.addEventListener("bufferedamountlow",()=>{this.closed||this.#a(Me.bufferedLow,{a:this.#B()})}),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(Me.sendHave,{bytes:ct.encode(JSON.stringify([...e]))})}sendHaveChange(e=[],t=[]){this.closed||this.#a(Me.sendHaveChange,{bytes:ct.encode(JSON.stringify({add:[...e],del:[...t]}))})}sendContribution(e,t){this.closed||this.#a(Me.sendContribution,{a:e?1:0,bytes:ct.encode(JSON.stringify(typeof t=="string"?t:null))})}sendFetching(e,t=0){this.closed||this.#a(Me.sendFetching,{a:t,bytes:ct.encode(String(e))})}request(e,t,{signal:r,expectedSize:s,onResult:i,onProgress:o,range:a}={}){let l=Dn(),c=!1,h=(p,g=null)=>{if(!c&&(c=!0,typeof i=="function"))try{let f=null;if(Number.isFinite(l)){let v=Dn();Number.isFinite(v)&&(f=v-l)}let m=g?.receivedBytes??0,y=Number.isFinite(u?.firstByteAt)&&Number.isFinite(l)?u.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(y)&&y>=0?y:null,metadataReceived:g?.metadataReceived===!0,draining:g?.draining===!0,closeReason:_a.has(this.closeReason)?this.closeReason:null})}catch{}},u=null;if(this.closed||this.#c||r?.aborted){let p=Promise.resolve(null);return h(this.closed?"closed":this.#c?"busy":"abort"),p}return new Promise(p=>{let g=()=>{u.id!==null&&!this.closed&&this.#a(Me.abort,{a:u.id,b:r?.reason===n.ABANDON_REASON?1:0})};u={id:null,firstByteAt:null,settled:!1,report:h,onProgress:o,startedAt:l,settle:m=>{u.settled||(u.settled=!0,r?.removeEventListener("abort",g),p(m))}};let f=s===void 0?NaN:Number.isSafeInteger(s)&&s>=0?s:-1;this.#h=u;try{a?this.#a(Me.requestRange,{a:Li(t),b:a.objectSize,bytes:ct.encode(JSON.stringify([String(e),a.start,a.end]))}):this.#a(Me.request,{a:Li(t),b:f,bytes:ct.encode(String(e))})}finally{this.#h=null}if(u.id===null){u.settle(null),h("closed");return}u.settled||r?.addEventListener("abort",g,{once:!0})})}close(e="host"){if(!this.closed){if(this.#t===null)return this.#b("host");this.#a(Me.close,{bytes:ct.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.#n.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.#r.values())t.settle(null),t.report("closed");this.#r.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=Hn,now:i=this.#f()}={}){if(this.#t===null)return;let o=this.#n.call(this.#t,e,i,(this.#S()?1:0)|(this.#l()?2:0),t,r,s);o&&this.#A(o)}#A({header:e,events:t}){let[r,s,i,o,a,l,c,h,u,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=h,this.lastServedAt=u,this.lastDeliveredAt=p,!Number.isNaN(f)&&this.#h&&(this.#h.id=f,this.#r.set(f,this.#h)),r!==this.#e&&this.#w(r),this.closed&&this.announced.clear();let y=++this.#M;for(let v of t)this.#O(v);if(y===this.#M&&this.#t!==null&&(this.#Y(g),m===1&&this.#B()<=Ta))return this.#a(Me.bufferedLow,{a:this.#B()});this.closed&&!this.#o&&this.#t!==null&&(this.#n.free(this.#t),this.#t=null,this.#n.links.delete(this),this.#I())}#w(e){let t=this.#n.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 Ue.sendText:{if(this.#k)return;let i=Ot.decode(t);try{this.channel.send(i)}catch{this.#k=!0,this.close("send-error")}return}case Ue.sendBinary:{if(this.#k)return;try{this.channel.send(t)}catch{this.#k=!0,this.close("serve-error")}return}case Ue.closed:{this.closeReason=Ot.decode(t),this.#I();try{this.channel.close()}catch{}try{this.pc.close()}catch{}this.onClose?.(this);return}case Ue.report:{let i=JSON.parse(Ot.decode(t)),o=i.id===null?this.#h:this.#r.get(i.id);if(!o)return;o.report(i.outcome,i),o.settled&&i.id!==null&&this.#r.delete(i.id);return}case Ue.resolved:{let i=Number.isNaN(r)?this.#h:this.#r.get(r);if(!i)return;i.settle(t);return}case Ue.haveChanged:{let i=JSON.parse(Ot.decode(t));this.onHaveChange?.(this,i);return}case Ue.scheduleChanged:{this.onScheduleChange?.(this);return}case Ue.serveRequest:case Ue.serveRange:{let i,o;if(e===Ue.serveRange){let[a,l,c]=JSON.parse(Ot.decode(t));i=a,o={start:l,end:c}}else i=Ot.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 Ue.uploadCancelled:{this.onUploadCancelled?.(this,s(0));return}case Ue.progress:{let i=s(0),o=s(1);for(let a of this.#r.values())if(!a.settled&&(a.firstByteAt===null&&(a.firstByteAt=Dn()),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}.`)}}#B(){try{return Math.max(0,Number(this.channel.bufferedAmount)||0)}catch{return 0}}#v(e,t){if(this.#t===null)return;let r=this.#B(),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(Me.serve,{a:0,b:r});if(s&&t&&this.#n.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(Me.serve,{a:0,b:r}):this.#a(Me.serveRange,{a:i,b:r,bytes:s.subarray(t.start*o,Math.min(i,t.end*o))})}this.#a(Me.serve,{a:s?1:0,b:r,bytes:s??Hn})}#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(Me.tick)},Math.max(0,e-this.#f())))}#I(){this.#s!==null&&globalThis.clearTimeout(this.#s),this.#s=null,this.#d=null}};var Oa=/^[0-9a-f]{64}$/u,oe={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},Ia=6e4,Ca=2e4,Na=new Set([oe.stale,oe.current,oe.valid,oe.live,oe.reserved,oe.suppresses]),Qt=class extends Error{constructor(e){super("Core discovery failed.",{cause:e})}},Hr=class{#n;#t;#e=null;#s=new Map;#d=new Map;#i=new WeakMap;#c=null;#o=null;#r=new WeakMap;#h=new WeakMap;#k=new Map;#M=1;#b=null;#S=null;constructor(e,t,r=()=>Date.now()){this.#n=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(oe.candidates,[]).map(e=>[e.pubkey,e]))}retire(){this.#e||(this.#S=null,this.#e=new Lt(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 Qt))throw r;this.retire();try{this.#t?.(r.cause)}catch{}return t(this.#e)}}#f(e,t){try{let r=this.#n(e,this.clock(),t);if(e===oe.candidates)return r.map(([s,i,o,a])=>({pubkey:s,have:i,ticket:o,at:a}));if(Na.has(e)&&typeof r!="boolean")throw new TypeError(`Core discovery answered operation ${e} with ${typeof r}.`);return r}catch(r){throw new Qt(r)}}#a(e,t){try{let{r,s}=this.#n(e,this.clock(),t);return this.#A(s),r}catch(r){throw new Qt(r)}}#A({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.#r.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.#r.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.#k:this.#h,i=s.get(e);return i===void 0&&t&&s.set(e,i=this.#M++),i}#B(e){let t=this.clock();return this.#S??=this.#f(oe.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(oe.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(oe.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"||!Oa.test(e)||!Array.isArray(t)||this.#l(()=>{this.#S=null,this.#f(oe.hint,[e,t.filter(s=>typeof s=="string"),we(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(oe.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(oe.holderAhead,[this.#w(e),t])},r=>r.holderAhead(e,t))}stale(e,t){return typeof t!="string"?!1:this.#l(()=>this.#f(oe.stale,[this.#w(e),t]),r=>r.stale(e,t))}forget(e){typeof e=="string"&&this.#l(()=>{this.#f(oe.forget,[e])},t=>t.forget(e))}current(e){return this.#l(()=>this.#w(e)!==null&&this.#f(oe.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(oe.current,[this.#w(o)])&&t(o)).map(o=>o.mediaType);return i.length===0?this.#b=null:this.#v(this.#a(oe.choose,[this.#B(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(oe.hinted,[r,this.#B(t)]))},r=>r.hinted(e,t))}begin(e){return this.#l(()=>!e||e!==this.#b?null:(this.#b=null,this.#a(oe.begin,[])===null?null:this.#c?.attempt??null),t=>t.begin(e))}valid(e){return this.#l(()=>{let t=e?this.#r.get(e):void 0;return t!==void 0&&this.#f(oe.valid,[t])},t=>t.valid(e))}replaced(e,t){return this.#l(()=>{let r=e?this.#r.get(e):void 0;return r!==void 0&&this.#a(oe.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.#r.get(e);r!==void 0&&this.#a(oe.allocated,[r,this.#O(t,!0)])},r=>r.allocated(e,t))}abandoned(e){this.#l(()=>{let t=e?this.#r.get(e):void 0;t!==void 0&&this.#a(oe.abandoned,[t])},t=>t.abandoned(e))}failed(e){this.#l(()=>{let t=this.#O(e,!1);t!==void 0&&this.#a(oe.failed,[t])},t=>t.failed(e))}end(e=this.window){return this.#l(()=>!!e&&e===this.#c&&this.#a(oe.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(oe.verified,[t])},t=>t.verified(e))}live(e=this.window){return this.#l(()=>!!e&&e===this.#c&&this.#f(oe.live,[]),t=>t.live(e))}reserved(){return this.#l(()=>this.#f(oe.reserved,[]),e=>e.reserved())}suppresses(e){return typeof e!="string"?!1:this.#l(()=>this.#f(oe.suppresses,[e]),t=>t.suppresses(e))}snapshot(){return this.#l(()=>({...this.#f(oe.snapshot,[]),counters:{...this.counters}}),e=>e.snapshot())}clear(){this.#l(()=>{this.#b=null,this.#S=null,this.#a(oe.clear,[])},e=>e.clear())}};var Pa=0,Ha=1,Da=2,Ua=3,_i=new TextEncoder,Un=new TextDecoder;function za(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:_t(n)}}async function qa(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 Fa=["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"],Oi=13,ja=15,zn=13,Ci=zn*8,Wa=5,It=n=>Number.isNaN(n)?null:n,Ii=(n,e)=>new Float64Array(n.memory.buffer,e,6);function Dr(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 Ur=(n,e)=>new Uint8Array(n.memory.buffer,n.rs_result_ptr(),e);function Ka(n,e){let t=Ur(n,e),r=new DataView(t.buffer,t.byteOffset,e),s=new Array(zn);for(let o=0;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 qn=class{#n;#t;#e=null;#s=new WeakMap;#d=0;constructor(e,t){this.#n=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.#n)}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=>Ii(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 It(this.#o(0))}rate(){return It(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=>It(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=>It(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]=Ii(t,t.rs_sel_summary(this.#c(e)));return{attempts:r,latencyMs:It(s),throughputBytesPerSecond:It(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(u=>!u.closed&&!u.busy&&!r.has(u.pubkey)&&u.have.has(t)),l=a.map(u=>this.#c(u)),c=l.length*4,h=o.rs_alloc(c);try{let u=new DataView(o.memory.buffer,h,c);l.forEach((g,f)=>u.setUint32(f*4,g,!0));let p=o.rs_sel_select(h,l.length,s,i);return p<0?null:a[l.indexOf(p)]}finally{o.rs_free(h,c)}},o=>o.select(e,t,r,s,i))}};async function Ni(n,{onFailure:e}={}){let{instance:t,module:r}=await qa(n),s=t.exports;for(let m of["memory","rs_alloc","rs_free","rs_call","rs_result_ptr",...Fa])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[...h.links])m.die()}},c=m=>{if(!i){l();try{e?.(m)}catch{}}},h={links:new Set,rangeUploads:typeof s.rs_link_serve_range=="function",newLink(m,y,v,b,T){if(i)throw new Error("The core has been retired.");return s.rs_link_new(m,y,v,b?1:0,T)},free(m){if(!i)try{s.rs_link_free(m)}catch(y){c(y)}},call(m,y,v,b,T,B,$){if(i)return null;try{let S=Dr(s,$,(L,U)=>y===ja&&h.rangeUploads?s.rs_link_serve_range(m,v,b,T,B,L,U):s.rs_link_call(m,y,v,b,T,B,L,U));if(S<0||Ss.rs_link_call(m,Oi,0,0,0,0,v,b));if(y<0)throw new Error(`Core link ${m} refused operation ${Oi}.`);return JSON.parse(Un.decode(Ur(s,y)))}catch(y){return c(y),null}}};function u(m,y){let v;try{v=_i.encode(JSON.stringify(y))}catch{return null}let b=Dr(s,v,(T,B)=>s.rs_call(m,T,B));return b<0?null:JSON.parse(Un.decode(Ur(s,b)))}function p(m,y,v){if(i)throw new Error("The core has been retired.");let b=_i.encode(JSON.stringify(v)),T=Dr(s,b,(B,$)=>s.rs_disc_call(m,y,B,$));if(T<0)throw new Error(`Core discovery refused operation ${m}.`);return JSON.parse(Un.decode(Ur(s,T)))}let g=({streamEvent:m,swarmId:y,revokedDelegationIds:v=[],delegationRevocations:b=[]})=>({streamEvent:m,swarmId:y,revokedDelegationIds:v,delegationRevocations:b}),f=Object.freeze({kind:"wasm",validStreamAuthorisation:m=>u(Pa,[m])===!0,verifyCommitmentDelegation:(m,y,v=Date.now())=>u(Ha,[m??null,g(y),v]),verifySegmentCommitment(m,y,v=Date.now()){let b;try{b=za(y.context)}catch{return null}return u(Da,[m??null,{...g(y),key:y.key,context:b,maxSegmentBytes:y.maxSegmentBytes,delegation:y.delegation??null},v])}});return Object.freeze({module:r,verifier:f,playerHint(m){if(i)return null;try{return u(Ua,m)}catch(y){return c(y),null}},retire:l,get retired(){return i},peerSelection(){if(o)throw new Error("This core instance already has a peer selection.");return o=new qn(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 Hr(p,c,m)},peerLink(m){return new Pr(m,h)},transfer(m){return Ti(s,m,()=>i,c)}})}var Va=new Uint8Array(0);var $a=Object.freeze({maxTransfers:2,maxSegmentBytes:16777216,maxActiveBytes:33554432,maxPending:32,maxPendingBytes:33554432,initTimeoutMs:5e3,operationTimeoutMs:5e3}),Ga=Object.freeze({maxTransfers:4,maxSegmentBytes:32*1048576,maxActiveBytes:64*1048576,maxPending:128,maxPendingBytes:64*1048576,initTimeoutMs:3e4,operationTimeoutMs:3e4}),Pi=n=>typeof n=="string"&&n.length===64&&/^[a-f0-9]{64}$/.test(n),je=n=>Number.isSafeInteger(n)&&n>=0,tr=n=>Number.isFinite(n)&&n>=0&&n<=Number.MAX_SAFE_INTEGER,er=n=>n===null||tr(n),Ya=(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||tr(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}},Ct=()=>new DOMException("Core transfer was cancelled.","AbortError");function Za(n={}){let e={};for(let[t,r]of Object.entries($a)){let s=n[t]??r;if(!Number.isSafeInteger(s)||s<1||s>Ga[t])throw new fe("invalid-limits");e[t]=s}return Object.freeze(e)}function Xa(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||!Pi(t.sha256)||!Array.isArray(t.pieces)||t.pieces.length<1||t.pieces.length>256||!t.pieces.every(Pi)||!tr(t.deadline)||!je(t.maxHolders)||t.maxHolders<1||t.maxHolders>32||!tr(t.originReserveMs)||n.peerOnly!==void 0&&typeof n.peerOnly!="boolean")throw new fe("invalid-transfer");return t}function Ja(n,e,t,r=!1){let[s,i,o]=e;if(!tr(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])&&er(l[1])&&er(l[2]))||(r?a.origin!=null:!Array.isArray(a.origin)||a.origin.length!==2||!a.origin.every(er))||!er(a.sharedFirstByteMs??null)||!er(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??((L,U)=>new Worker(L,U)),l;try{l=a(e,{type:"module",name:"relayswarm-transfer"})}catch{throw new fe("worker-unavailable")}let c="loading",h=null,u=0,p=0,g=0,f=0,m=new Map,y=new Map,v=L=>{L.signal?.removeEventListener("abort",L.onAbort),y.get(L.id)===L&&(y.delete(L.id),f-=L.size)},b=(L,U=!0)=>{if(!(c==="stopped"||c==="failed")){c=U?"failed":"stopped",h=L.code??L.name,l.removeEventListener("message",$),l.removeEventListener("error",T),l.removeEventListener("messageerror",T),r?.removeEventListener("abort",B);for(let C of m.values())clearTimeout(C.timer),C.settled||C.reject(L);m.clear(),g=0;for(let C of y.values())C.closed=!0,v(C);try{l.terminate()?.catch?.(()=>{})}catch{}if(U)try{s?.(L)?.catch?.(()=>{})}catch{}}},T=L=>{L?.preventDefault?.(),b(new fe("worker-error"))},B=()=>b(Ct(),!1),$=({data:L})=>{if(!L||L.v!==1||!je(L.id)||!m.has(L.id))return;let U=m.get(L.id);if(m.delete(L.id),g-=U.bytes,clearTimeout(U.timer),L.ok!==!0){let C=new fe(typeof L.error=="string"&&/^[a-z-]{1,40}$/.test(L.error)?L.error:"invalid-response");U.settled||U.reject(C),(L.fatal||L.ok!==!1)&&b(C)}else if(["init","new","free"].includes(U.op)?L.result!==!0:!Ya(L.result,U.size)){let C=new fe("invalid-response");U.settled||U.reject(C),b(C)}else U.settled||U.resolve(L.result)},S=(L,U,C,F=0,O=[],d=!1)=>c==="stopped"||c==="failed"?Promise.reject(new fe("closed")):!d&&m.size>=o.maxPending||g+F>o.maxPendingBytes?Promise.reject(new fe("queue-limit")):new Promise((w,A)=>{let x=++u,R={resolve:w,reject:A,handle:U,bytes:F,op:L,size:y.get(U)?.size??o.maxSegmentBytes,settled:!1,timer:setTimeout(()=>b(new fe(L==="init"?"init-timeout":"operation-timeout")),L==="init"?o.initTimeoutMs:o.operationTimeoutMs)};m.set(x,R),g+=F;try{l.postMessage({v:1,id:x,op:L,handle:U,input:C},O)}catch{b(new fe("worker-message"))}});l.addEventListener("message",$),l.addEventListener("error",T),l.addEventListener("messageerror",T),r?.addEventListener("abort",B,{once:!0}),r?.aborted&&B();try{await S("init",null,{module:n,limits:o})}catch(L){throw b(L),L}if(c!=="loading")throw new fe("closed");return c="ready",Object.freeze({snapshot:()=>({state:c,reason:h,transfers:y.size,activeBytes:f,pending:m.size,pendingBytes:g}),stop:B,async transfer(L,{signal:U}={}){if(c!=="ready")throw new fe("closed");if(U?.aborted)throw Ct();let C=Xa(L,o);if(y.size>=o.maxTransfers||f+C.size>o.maxActiveBytes)throw new fe("transfer-limit");let F={id:++p,size:C.size,closed:!1,signal:U,release:null};y.set(F.id,F),f+=C.size;let O=()=>{if(F.release)return F.release;F.closed=!0;for(let w of m.values())w.handle===F.id&&!w.settled&&(w.settled=!0,w.reject(Ct()));return F.release=S("free",F.id,null,0,[],!0).then(()=>!0,()=>!1).finally(()=>v(F))};F.onAbort=()=>{O()},U?.addEventListener("abort",F.onAbort,{once:!0});try{await S("new",F.id,C)}catch(w){throw F.closed||v(F),w}if(F.closed||U?.aborted)throw O(),Ct();let d=async(w,A)=>{if(F.closed)throw new fe("closed-transfer");try{let x=Ja(w,A,o.maxSegmentBytes,C.peerOnly===!0),R=0,P=[];if(w==="delivered"){if(R=x[3].byteLength,g+R>o.maxPendingBytes)throw new fe("queue-limit");x[3]=x[3].slice(),P=[x[3].buffer]}let N=await S(w,F.id,x,R,P);if(F.closed)throw Ct();return N}catch(x){throw O(),x}};return Object.freeze({start:(w,A)=>d("start",[w,A]),delivered:(w,A,x,R)=>d("delivered",[w,A,x,R]),failed:(w,A)=>d("failed",[w,A]),progress:(w,A,x)=>d("progress",[w,A,x]),tick:w=>d("tick",[w]),free:O,cancel:O,get closed(){return F.closed}})}})}function Di(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 ht(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 Ui(n,e,t,r,{signal:s,onIgnored:i,onResult:o}={}){let a=Di(e,t,r);return!a||typeof n?.Loader!="function"||typeof e?.url!="string"||s?.aborted?(ht(o,s?.aborted?"abort":"invalid-request",t,r),Promise.resolve(null)):new Promise(l=>{let c=null,h=!1,u=(f,m,y=f?.byteLength??null,v=null)=>{if(!h){h=!0,s?.removeEventListener("abort",p);try{c?.destroy?.()}catch{}ht(o,m,t,r,y,v),l(f)}},p=()=>{try{c?.abort?.()}catch{}u(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 u(null,"abort");let m=g(f?.data);if(!m&&!h)try{i?.()}catch{}u(m,m?"payload":"wrong-size",f?.data?.byteLength??null,f?.code)},onError:f=>u(null,s?.aborted?"abort":"error",null,f?.code),onTimeout:()=>u(null,s?.aborted?"abort":"timeout"),onAbort:()=>u(null,"abort")})}catch{u(null,"exception")}})}function Qa(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 zi(n,e,t,{signal:r,onIgnored:s,onResult:i,fetchImpl:o=globalThis.fetch}={}){let a=Di(n,e,t);if(!a||typeof n?.url!="string"||typeof o!="function"||r?.aborted)return ht(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 ht(i,r?.aborted?"abort":"error",e,t),null}let c=(h=null)=>{try{s?.()}catch{}return ht(i,"wrong-size",e,t,h,l.status),null};try{if(l.status!==206||!Qa(l.headers.get("content-range"),a)){try{await l.body?.cancel()}catch{}return l.status===200||l.status===206?c():(ht(i,"error",e,t,null,l.status),null)}let h=new Uint8Array(await l.arrayBuffer());return h.byteLength!==t-e?c(h.byteLength):(ht(i,"payload",e,t,h.byteLength,l.status),h)}catch{return ht(i,r?.aborted?"abort":"error",e,t,null,l?.status),null}}var Te=Symbol("relayswarm-warm-ahead"),We=24*1024*1024,qi=3,Fn=4,rr=8e3,el=100,dt=n=>{let{start:e,duration:t}=n?.context?.frag??{};return Number.isFinite(e)&&e>=0&&Number.isFinite(t)&&t>0&&Number.isFinite(e+t)},jn=(n,e)=>dt(n)&&n.context.frag.start<=e&&en?.key===e?.key&&n?.scope===e?.scope&&dt(n)&&dt(e)&&n.context.frag.start===e.context.frag.start&&n.context.frag.duration===e.context.frag.duration,tl=(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 Fi({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:h=null,startupCommit:u=null,startupRecovery:p=()=>2e3}){let g=!1,f=0,m=null,y=null,v=[],b,T,B=null,$=0,S=new Map,L=new Set,U=new Map,C=new Set,F=new Set,O=new Map,d={enabled:typeof h=="function",state:h?"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},w={started:0,verified:0,rejected:0,cancelled:0,coalesced:0,promotions:0,localReuseBytes:0,verifiedBytes:0,verifiedPeerBytes:0,consumedPeerBytes:0,cacheBytes:0,highWaterBytes:0},A=()=>d.reserved+[...U.values()].reduce((E,k)=>E+k.reserved,0),x=()=>new Set([...S.keys(),...U.keys(),...d.owner?[d.own.key]:[]]).size,R=()=>d.state==="buffering"?Fn:qi,P=E=>U.get(E.key)===E&&!E.finished,N=E=>{let k=S.get(E);k&&(w.cacheBytes-=k.data.byteLength,S.delete(E))},M=(E,k)=>{P(E)&&(E.finished=!0,U.delete(E.key),C.delete(E),m===E&&(m=null),E.reserved=0,E.finish(k),d.checking&&(d.recheck=!0),W(),queueMicrotask(q))},H=E=>{P(E)&&(w.cancelled++,E.cancel(),M(E,null))},D=()=>{(d.state==="idle"||d.state==="buffering")&&Q("cancelled","cleared",!g),d.planningServiceMs=null,f++,v=[],B=null;for(let E of[...U.values()])H(E);for(let E of S.keys())N(E);for(let E of[...F])E(!0)},q=()=>{if(g||m||!l()||!v.length||L.size+C.size>1||!c&&d.state!=="buffering"||d.state==="buffering"&&(!d.permit||d.checking)||d.state==="buffering"&&!jr()||d.state==="buffering"&&x()>=R())return;let E=v.shift();if(S.has(E.key)||U.has(E.key)){queueMicrotask(q);return}for(;x()>=qi&&S.size&&d.state!=="buffering";)N(S.keys().next().value);if(x()>=R())return;let k=new AbortController,z=f,Z=b,_=T,K,J,X,G={...E,reserved:0,finished:!1,waiters:new Set,genuineAt:null,promise:new Promise(te=>{X=te}),noteDemand(){G.genuineAt??=performance.now(),E.context[Te]?.onGenuine?.()},genuine(){if(!P(G))return null;let te=[...G.waiters].find(xe=>xe.pendingTerminal&&Ae(xe.context)?.key===G.key);return te&&G.genuineAt!==null?{at:G.genuineAt,context:te.context}:null},promote(){clearTimeout(J)},finish:te=>X(te),cancel(){k.abort(),clearTimeout(J);try{K?.abort(),K?.destroy()}catch{}}};m=G,U.set(G.key,G),J=setTimeout(()=>H(G),rr),(async()=>{try{let te=await t(E.context,k.signal);if(k.signal.aborted||g||z!==f||!P(G)||!l())return null;if(!te||!Number.isSafeInteger(te.size)||te.size<1||te.size>We)return w.rejected++,null;for(;w.cacheBytes+A()+te.size>We&&S.size&&d.state!=="buffering";)N(S.keys().next().value);if(w.cacheBytes+A()+te.size>We)return w.rejected++,null;if(G.reserved=te.size,!s(A()))return G.reserved=0,w.rejected++,null;w.highWaterBytes=Math.max(w.highWaterBytes,w.cacheBytes+A());let xe=E.context[Te]={peerBytes:0,genuine:()=>G.genuine(),startupDependency:()=>{if(!j()||!P(G)||!l()||!pe(E))return null;try{return me()===null||!j()?null:{at:d.entryAt,deadline:d.deadline,signal:d.controller.signal,context:E.context}}catch{return null}}};K=new n(Z),w.started++;let ue=performance.now(),he=await new Promise(le=>K.load(E.context,_,{onSuccess:(be,ce,Pe,Ce)=>le({response:be,stats:ce,details:Ce,serviceMs:tl(ce,te.size,ue,performance.now())}),onError:(...be)=>le({failure:{name:"onError",args:be,stats:K.stats}}),onTimeout:(...be)=>le({failure:{name:"onTimeout",args:be,stats:K.stats}}),onAbort:(...be)=>le({failure:{name:"onAbort",args:be,stats:K.stats}}),onProgress:be=>{if(be?.loaded>te.size){k.abort();try{K.abort()}catch{}le(null)}}}));if(he?.failure)return k.signal.aborted||g||z!==f||!P(G)?null:(w.rejected++,he);if(!he||k.signal.aborted||g||z!==f||!P(G)||!await r(te,he.response.data,E.context,k.signal))return w.rejected++,null;if(k.signal.aborted||g||z!==f||!P(G))return null;let de=he.response.data;if(de.byteLength!==te.size)return w.rejected++,null;if(G.reserved=0,i?.(te,de,E.context)===!1)return null;let ye={...he,context:E.context,scope:E.scope,data:de,permit:te,peerBytes:xe.peerBytes,accept:xe.accept};return S.set(E.key,ye),w.cacheBytes+=de.byteLength,w.verified++,w.verifiedBytes+=de.byteLength,w.verifiedPeerBytes+=xe.peerBytes,j()&&P(G)&&f===z&&E.scope===y&&pe(E)&&(d.planningServiceMs=he.serviceMs),ye}catch{return k.signal.aborted||w.rejected++,null}finally{clearTimeout(J);try{K?.destroy()}catch{}}})().then(te=>M(G,te))},ee=(E,k,z,Z)=>{B=null;let _=Ae(E);if(!_||g)return null;y!==_.scope&&(y!==null&&D(),y=_.scope),b=k,T=z;let K=[];try{K=e(E).map(Ae).filter(Boolean).filter(X=>X.scope===y).slice(0,2)}catch{}let J=new Set([_.key,...K.map(X=>X.key)]);for(let X of S.keys())J.has(X)||N(X);for(let X of[...U.values()])J.has(X.key)||H(X);return v=K,dt(_)&&K.every(dt)&&(B={own:ae(_),upcoming:K.map(ae),owner:Z}),_},j=()=>{if(d.state!=="buffering"||g||d.revision!==f||d.owner?.pendingTerminal!==d.terminal||d.terminal.settled)return!1;let E=!1;try{E=ut(Ae(d.terminal.context),d.identity)&&ut(Ae(d.own.context),d.identity)&&d.terminal.context.url===d.contextUrl&&d.terminal.context.frag.url===d.fragUrl}catch{}return E?!0:(Q("cancelled","context-changed"),!1)},V=E=>({code:0,text:"RelaySwarm startup buffer unavailable",startupBufferReason:E}),re=E=>e(E.context).map(Ae).filter(Boolean).filter(k=>k.scope===y&&dt(k)).slice(0,2),ae=E=>{let{key:k,scope:z,context:{url:Z,frag:_}}=Ae(E.context);return{key:k,scope:z,context:{url:Z,frag:_,part:null,responseType:"arraybuffer"}}},ge=(E,k)=>({...ae(E),identity:ae(E),parent:ae(k)}),ne=E=>{try{return ut(Ae(E.context),E.identity)&&re(E.parent).some(k=>ut(k,E.identity))}catch{return!1}},pe=E=>{if(!j()||B?.owner!==d.terminal.id)return!1;let k=d.plan.find(z=>ut(z.identity,E));return!!(k&&ne(k))},Q=(E,k,z=!0)=>{if(!["idle","buffering"].includes(d.state))return;let Z=d.owner,_=d.terminal;d.state=E,d.reason=k,E==="failed"&&d.failures++,E==="cancelled"&&d.cancellations++,clearTimeout(d.timer),d.timer=null,clearTimeout(d.poll),d.poll=null,d.controller?.abort(),d.releasePins?.(),d.owner=null,d.terminal=null,d.response=null,d.reserved=0,v=[],d.plan=[],d.cursor=null,d.frozenStart=null,d.planningServiceMs=null;for(let K of[...U.values()])H(K);for(let K of S.keys())N(K);if(!(!Z||!_||_.settled||Z.pendingTerminal!==_)){_.settled=!0,Z.pendingTerminal=null,Z.token++,Z.stats.aborted=!0;try{Z.inner.abort()}catch{}!z||g||(E==="cancelled"?_.callbacks.onAbort?.(Z.stats,_.context,null):_.callbacks.onError?.(V(k),_.context,null,Z.stats))}},me=()=>{let E;try{E=h()}catch{return Q("failed","target-threw"),null}return E===null?(Q("cancelled","target-unavailable"),null):!Number.isFinite(E)||E<0?(Q("failed","invalid-target"),null):(d.targetTime=E,E)},et=()=>{let E;try{E=p(d.own.context)}catch{}return!Number.isFinite(E)||E<0?(Q("failed","invalid-recovery"),null):(d.requiredHeadroomMs=E,E)},Ie=(E,k)=>{if(!j()||d.checking)return;if(d.frozenStart!==null&&E>=d.frozenStart&&(d.frozenStart=null),d.plan.some(_=>!ne(_))||d.cursor&&!ne(d.cursor))return Q("cancelled","context-changed");for(;d.plan.length;){let _=d.plan[0],K=S.get(_.key),J=U.get(_.key);if(_.context.frag.start+_.context.frag.duration>E||J||K&&O.has(K.permit.key)||[...L].some(X=>X.pendingTerminal&&Ae(X.context)?.key===_.key))break;if(!K){if(!d.hopAvailable)return;d.hopAvailable=!1}if(d.cursor=_,d.plan.shift(),v=v.filter(X=>X.key!==_.key),!j()||d.checking)return;N(_.key)}let z=d.plan[0];if(d.verified&&d.response&&d.plan.length===2&&S.size===2&&!m&&!U.size&&!L.size&&!C.size&&jn(z,E)&&d.plan.every(_=>S.has(_.key)&&!O.has(S.get(_.key).permit.key))){let _=St(E);_.end!==null&&(_.end-E)*1e3S.has(_.key)&&!O.has(S.get(_.key).permit.key))){let _=St(E);_.rows.length===d.plan.length+1&&_.end!==null&&(_.end-E)*1e3_.context.frag.start)?d.cursor:_??d.own,J;try{J=re(K)[0]}catch{return Q("cancelled","context-changed")}if(!J)return;let X=K.context.frag.start+K.context.frag.duration;if(Math.abs(J.context.frag.start-X)>.001||J.key===d.own.key||d.plan.some(te=>te.key===J.key))return Q("cancelled","context-changed");let G=ge(J,K);if(J.context.frag.start+J.context.frag.duration<=E){if(!d.hopAvailable)return;d.hopAvailable=!1,d.cursor=G;return}d.plan.push(G),v.push(J)}},jr=()=>{if(!j()||d.checking)return!1;let E=me();if(E===null||!j())return!1;let k=et();if(k===null||!j()||(Ie(E,k),!j()||d.checking||!v.length))return!1;if(d.frozenStart!==null&&EE)return!0;let z=v[0],Z=d.plan.findIndex(_=>_.key===z.key);if(Z<0)return Q("cancelled","context-changed"),!1;if(z.context.frag.start+z.context.frag.duration<=E+(k+(d.planningServiceMs??0))/1e3){if(!d.hopAvailable)return!1;d.hopAvailable=!1,d.cursor=d.plan[Z],d.plan.splice(Z,1),v.shift(),Ie(E,k);let _=v[0]?.context.frag.start;return _>E&&(d.frozenStart=_),!1}return!0},ft=()=>{if(d.poll!==null||!j())return;let E=d.deadline-performance.now();if(E<=0)return Q("failed","deadline");d.poll=setTimeout(()=>{if(d.poll=null,!!j()){if(!d.checking){d.hopAvailable=!0;let k=me();if(k===null||!j())return;if(!l())return Q("cancelled","not-allowed");let z=et();if(z===null||!j()||(Ie(k,z),!j()))return;W(k),queueMicrotask(q)}ft()}},Math.min(el,E))},St=(E,k=null)=>{let z=d.verified&&d.response?[{...d.own,permit:d.permit}]:[],Z=(k??[...z,...S.values()]).filter(X=>X.scope===y&&dt(X)).sort((X,G)=>X.context.frag.start-G.context.frag.start),_=null,K=null,J=[];for(let X of Z){let G=X.context.frag.start,te=G+X.context.frag.duration;_===null?G<=E&&EK&&(K=te,J.push(X))}return d.verifiedStart=_,d.verifiedEnd=K,{start:_,end:K,rows:J}},nr=(E=void 0)=>{if(!j())return null;if(E===void 0&&(E=me()),E===null||!j())return;if(!l())return Q("cancelled","not-allowed");let k;try{k=p(d.own.context)}catch{}if(!Number.isFinite(k)||k<0)return Q("failed","invalid-recovery");d.requiredHeadroomMs=k;let z=St(E);if(!(z.end===null||(z.end-E)*1e3new Promise((k,z)=>{let Z=!1,_=J=>{Z||(Z=!0,E.removeEventListener("abort",K),J?k():z(null))},K=()=>_(!1);if(E.addEventListener("abort",K,{once:!0}),E.aborted)return K();try{Promise.resolve(u(Object.freeze({signal:E}))).then(()=>_(!0),()=>_(!1))}catch{_(!1)}}),W=async(E=void 0)=>{if(!j()||d.checking||!d.verified)return;let k=nr(E);if(!k)return;d.checking=!0;let z=d.owner,Z=d.terminal,_=f,K=new Map,J=[],X=!0,G=()=>{if(X){X=!1;for(let ue of J){let he=(O.get(ue)??0)-1;he>0?O.set(ue,he):O.delete(ue)}d.releasePins===G&&(d.releasePins=null)}};d.releasePins=G;let te=()=>[...K.values()].some(({key:ue,row:he,identity:de})=>S.get(ue)!==he||!ut(Ae(he.context),de)||he.data.byteLength!==he.permit.size)?(Q("failed","coverage-evicted"),!1):[...K.values()].some(({key:ue,row:he})=>!pe({key:ue,scope:he.scope,context:he.context}))?(Q("cancelled","context-changed"),!1):!0,xe=async({covered:ue})=>{for(let[ye,le]of S)ue.rows.includes(le)&&!K.has(le)&&(K.set(le,{key:ye,row:le,identity:Ae(le.context)}),J.push(le.permit.key),O.set(le.permit.key,(O.get(le.permit.key)??0)+1));let he=[{context:d.own.context,permit:d.permit},...ue.rows.filter(ye=>ye.context!==d.own.context)],de=await Promise.all(he.map(ye=>t(ye.context,d.controller.signal)));return()=>{if(!j()||f!==_)return;if(de.some((ce,Pe)=>!ce||ce.key!==he[Pe].permit.key||ce.size!==he[Pe].permit.size||ce.sha256!==he[Pe].permit.sha256))return Q("failed","authority-changed");let ye=me();if(ye===null||!j())return;if(!l())return Q("cancelled","not-allowed");let le;try{le=p(d.own.context)}catch{}if(!Number.isFinite(le)||le<0)return Q("failed","invalid-recovery");if(d.requiredHeadroomMs=le,de.some((ce,Pe)=>typeof ce.current!="function"||ce.current(he[Pe].context)!==!0))return Q("failed","authority-changed");if(!j())return;if(performance.now()>=d.deadline)return Q("failed","deadline");if(!te())return;let be=St(ye,ue.rows);if(!(be.end===null||(be.end-ye)*1e3=d.deadline)return Q("failed","deadline");if(d.commitCompleted=!0,!te())return;let le=nr();if(!le||(ue=await xe(le),!ue()))return}let he=d.response,de=Z.context[Te];if(o?.(Z.context,he[0].data.byteLength,de?.peerBytes??0),!j())return;if(!l())return Q("cancelled","not-allowed");if((de?.commit??de?.accept)?.(Z.context),!j())return;de?.peerBytes>0&&(w.consumedPeerBytes+=de.peerBytes),d.state="ready",d.reason=null,d.released++,d.planningServiceMs=null,clearTimeout(d.timer),d.timer=null,clearTimeout(d.poll),d.poll=null,d.reserved=0;let ye=d.controller;if(d.owner=null,d.terminal=null,d.response=null,d.plan=[],d.cursor=null,d.frozenStart=null,!c){v=[];for(let le of[...U.values()])H(le)}try{z.deliver(Z,"onSuccess",he)}finally{try{ye.abort()}finally{de?.notify?.()}}}catch{j()&&Q("failed","authority-refused")}finally{G(),d.checking=!1,d.state==="buffering"&&(queueMicrotask(q),d.recheck&&(d.recheck=!1,queueMicrotask(W)))}},ve=(E,k,z,Z)=>{if(!d.enabled)return!0;if(d.state==="failed"||d.state==="cancelled")return d.state==="cancelled"&&(E.stats.aborted=!0),E.deliver(k,d.state==="cancelled"?"onAbort":"onError",d.state==="cancelled"?[E.stats,k.context,null]:[V(d.reason),k.context,null,E.stats]),!1;if(!z)return d.state==="idle"&&k.context.frag?.type==="main"&&k.context.frag.sn!=="initSegment"?(d.state="failed",d.reason="unsupported-context",d.failures++,E.deliver(k,"onError",[V(d.reason),k.context,null,E.stats]),!1):!0;if(d.state==="buffering")return Q("cancelled","superseded"),E.deliver(k,"onAbort",[E.stats,k.context,null]),!1;if(d.state!=="idle")return!0;let _=performance.now(),K=Z?.loadPolicy?.maxLoadTimeMs??Z?.timeout;if(Object.assign(d,{state:"buffering",owner:E,terminal:k,own:z,revision:f,reserved:We,entryAt:_,identity:{key:z.key,scope:z.scope,context:{frag:{start:z.context.frag.start,duration:z.context.frag.duration}}},contextUrl:k.context.url,fragUrl:k.context.frag.url,controller:new AbortController,deadline:_+Math.min(rr,Number.isFinite(K)&&K>0?K:rr)}),d.plan=(B?.upcoming??[]).map(J=>ge(J,z)),B?.owner===k.id&&(B.rolling=d.plan),d.cursor=null,k.context[Te]={peerBytes:0,genuine:()=>j()?{at:_,context:k.context}:null},!dt(z)||!l())return Q("failed","not-allowed"),!1;if(E.config.progressive===!0)return Q("failed","progressive-unsupported"),!1;if(me()===null||!j())return!1;try{if(!s(A()))return Q("failed","reservation-refused"),!1}catch{return Q("failed","reservation-refused"),!1}return j()?l()?(d.timer=setTimeout(()=>Q("failed","deadline"),Math.max(0,d.deadline-performance.now())),ft(),Promise.resolve().then(()=>j()?t(z.context,d.controller.signal):null).then(J=>{if(j()){if(!J||!Number.isSafeInteger(J.size)||J.size<1||J.size>We)return Q("failed","first-authority-refused");if(d.permit=J,d.reserved=J.size,!s(A()))return Q("failed","reservation-refused");w.highWaterBytes=Math.max(w.highWaterBytes,w.cacheBytes+A()),ie(),queueMicrotask(q)}}).catch(()=>{j()&&Q("failed","first-authority-refused")}),!0):(Q("cancelled","not-allowed"),!1):!1},ie=async()=>{if(!(!j()||!d.response||!d.permit||d.verifying||d.verified)){d.verifying=!0;try{let E=d.response[0].data,k=d.permit;if(!(E instanceof ArrayBuffer)||E.byteLength!==k.size||!await r(k,E,d.own.context,d.controller.signal))return j()&&Q("failed","first-integrity");if(!j())return;d.verified=!0,w.verified++,w.verifiedBytes+=E.byteLength,w.verifiedPeerBytes+=d.terminal.context[Te]?.peerBytes??0,W()}catch{j()&&Q("failed","first-integrity")}finally{d.verifying=!1}}};return{Loader:class{static relayswarmShadow=!0;constructor(k){this.config=k,this.inner=new n(k),this.stats=this.inner.stats,this.context=null,this.token=0}load(k,z,Z){this.abort(),this.context=k;let _={id:++$,context:k,callbacks:{...Z},settled:!1};this.pendingTerminal=_,Z={...Z};for(let xe of["onSuccess","onError","onTimeout","onAbort"])Z[xe]=(...ue)=>this.complete(_,xe,ue);let K=++this.token,J=ee(k,this.config,z,_.id),X=J&&S.get(J.key);if(!ve(this,_,J,z))return;let G=!X&&J&&U.get(J.key),te=X??G?.promise;if(te){G&&(w.coalesced++,G.waiters.add(this),this.warmPending=G,G.noteDemand(),m===G&&C.size===0&&(m=null,C.add(G),G.promote(),w.promotions++)),this.reuseAbort=new AbortController;let xe=f,ue=null,he,de=null,ye=()=>K===this.token,le=()=>{if(clearTimeout(he),F.delete(be),de!==null){let ce=O.get(de)-1;ce>0?O.set(de,ce):O.delete(de),de=null}},be=(ce=!1)=>{if(ce&&(le(),this.reuseAbort.abort()),!ye()||ue||this.originStarted)return;this.originStarted=!0,clearTimeout(he);let Pe={...Z,onProgress:(...Ce)=>{!ye()||ue==="cache"||(Ce[2]?.byteLength>0&&(ue="origin",this.reuseAbort.abort(),le()),Z.onProgress?.(...Ce))}};for(let Ce of["onSuccess","onError","onTimeout","onAbort"])Pe[Ce]=(...Ht)=>{!ye()||ue==="cache"||(ue="origin",this.reuseAbort.abort(),le(),Z[Ce]?.(...Ht))};this.start(k,z,Pe,K)};this.cancelReuse=()=>{le(),this.reuseAbort.abort()},F.add(be),Promise.resolve(te).then(async ce=>{if(!ye())return;if(this.releasePending(),g||!ce||xe!==f)return be(!0);if(ce.failure){let{name:Gn,args:Wr,stats:Yn}=ce.failure;ue="origin",le(),this.reuseAbort.abort(),Yn&&Object.assign(this.stats,Yn),Gn==="onError"?Z.onError(Wr[0],k,Wr[2],this.stats):Z[Gn](this.stats,k,Wr[2]);return}de=ce.permit.key,O.set(de,(O.get(de)??0)+1);let Pe=Math.max(0,Math.min(25,a(k)||0));Pe>0?he=setTimeout(be,Pe):be();let Ce;try{Ce=await t(k,this.reuseAbort.signal)}catch{}if(!ye()||ue==="origin")return;if(g||xe!==f)return be(!0);if(!Ce||Ce.key!==ce.permit.key||Ce.size!==ce.permit.size||Ce.sha256!==ce.permit.sha256)return N(J.key),be();ue="cache",le(),this.originStarted&&this.inner.abort(),Object.assign(this.stats,ce.stats);let Ht=ce.data.slice(0);w.localReuseBytes+=Ht.byteLength,ce.accepted||(ce.accepted=!0,ce.accept?.(k),w.consumedPeerBytes+=ce.peerBytes),o?.(k,Ht.byteLength,ce.peerBytes),Z.onSuccess({...ce.response,data:Ht},this.stats,k,ce.details),queueMicrotask(q)})}else this.start(k,z,Z,K);queueMicrotask(q)}start(k,z,Z,_){L.add(this),L.size+C.size>1&&m&&H(m);let K=this.pendingTerminal,J=()=>{L.delete(this),queueMicrotask(q)},X={...Z};X.onProgress=(...G)=>{if(!(g||_!==this.token||!K||K.settled||this.pendingTerminal!==K)){if(d.owner===this&&(G[0]?.loaded>(d.permit?.size??We)||G[2]?.byteLength>(d.permit?.size??We)))return Q("failed","first-oversize");if(d.owner===this&&G[2]!==null&&G[2]!==void 0){j();return}Z.onProgress?.(...G)}};for(let G of["onSuccess","onError","onTimeout","onAbort"])X[G]=(...te)=>{J(),_===this.token&&Z[G]?.(...te)};this.inner.load(k,z,X)}releasePending(){let k=this.warmPending;this.warmPending=null,k&&(k.waiters.delete(this),k.waiters.size||k.context[Te]?.onGenuine?.(),C.has(k)&&!k.waiters.size&&H(k))}complete(k,z,Z){if(!(!k||k.settled||this.pendingTerminal!==k)){if(d.owner===this&&d.terminal===k&&d.state==="buffering"){if(z==="onSuccess"){let _=Z[0]?.data;if(!(_ instanceof ArrayBuffer)||_.byteLength>(d.permit?.size??We))return Q("failed","first-oversize");d.response=Z,ie();return}d.state=z==="onAbort"?"cancelled":"failed",d.reason=z==="onAbort"?"origin-abort":"origin-error",z==="onAbort"?d.cancellations++:d.failures++,clearTimeout(d.timer),clearTimeout(d.poll),d.poll=null,d.controller?.abort(),d.releasePins?.(),d.owner=null,d.terminal=null,d.response=null,d.reserved=0,v=[],d.plan=[],d.cursor=null,d.frozenStart=null,d.planningServiceMs=null;for(let _ of[...U.values()])H(_);for(let _ of S.keys())N(_)}this.deliver(k,z,Z)}}deliver(k,z,Z){!k||k.settled||this.pendingTerminal!==k||(z!=="onSuccess"&&B?.owner===k.id&&(B=null),k.settled=!0,this.pendingTerminal=null,k.callbacks[z]?.(...Z))}cancel(k){let z=this.pendingTerminal;d.owner===this&&d.terminal===z&&Q("cancelled","caller-abort",!k&&!g),z&&B?.owner===z.id&&(B=null),this.token++,this.originStarted=!1,this.cancelReuse?.(),this.releasePending(),L.delete(this),z&&(this.stats.aborted=!0),k&&z&&(z.settled=!0,this.pendingTerminal=null);try{k?this.inner.destroy():this.inner.abort()}finally{k||this.complete(z,"onAbort",[this.stats,z?.context,null])}}abort(){this.cancel(!1)}destroy(){this.cancel(!0)}getCacheAge(){return this.inner.getCacheAge?.()??null}getResponseHeader(k){return this.inner.getResponseHeader?.(k)??null}},clear:D,startupSnapshot:()=>({enabled:d.enabled,state:d.state,reason:d.reason,heldObjects:d.state==="buffering"?x():0,heldBytes:d.state==="buffering"?w.cacheBytes+A():0,targetTime:d.targetTime,verifiedStart:d.verifiedStart,verifiedEnd:d.verifiedEnd,requiredHeadroomMs:d.requiredHeadroomMs,planningServiceMs:d.planningServiceMs,released:d.released,failures:d.failures,cancellations:d.cancellations,commitStarted:d.commitStarted,commitCompleted:d.commitCompleted,limits:{objects:Fn,bytes:We,deadlineMs:rr}}),contains(E){if(g||!l()||!Number.isFinite(E))return!1;for(let z of[...U.values(),...S.values()])if(z.scope===y&&jn(z,E))return!0;let k=B;if(!k||k.own.scope!==y||!jn(k.own,E))return!1;try{let z=k.rolling??e(k.own.context).map(Ae).filter(Boolean).filter(_=>_.scope===y).slice(0,2),Z=new Map([k.own,...z].map(_=>[_.key,_]));return(k.rolling?z.some(_=>!ne(_)):z.length!==k.upcoming.length||z.some((_,K)=>!ut(_,k.upcoming[K])))||[...U,...S].some(([_,K])=>!ut({...K,key:_},Z.get(_)))?(B=null,!1):!0}catch{B=null}return!1},pinned:E=>O.has(E),release(E){for(let[k,z]of S)z.permit.key===E&&N(k)},stop(){g=!0,D()},snapshot:()=>({...w,reservationBytes:A(),active:+!!m,promoted:C.size,trackedObjects:x(),queued:v.length,cacheObjects:S.size,limits:{objects:R(),bytes:We,speculativeWholeRequests:1,deadlineMs:rr,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},h=!1,u=null,p=v=>{if(!v.waiting)return;let b=Math.max(0,n()-v.queuedAt);c.waited++,c.waitTotalMs+=b,c.waitMaxMs=Math.max(c.waitMaxMs,b)},g=(v,b)=>{a.get(v.link)===v&&(a.delete(v.link),p(v),c[b]++,i(b),v.resolve(null))},f=(v,b=!1)=>{l.delete(v)&&(v.active=!1,b||t(v.charge),queueMicrotask(m))},m=()=>{if(clearTimeout(u),u=null,!h)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 b=v.deadline-n();u=setTimeout(m,Math.max(1,Math.ceil(Math.min(b,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)}},y=v=>{for(let b of[...a.values()])(!v||b.link===v)&&g(b,"cancelled");for(let b of[...l])(!v||b.link===v)&&(c.cancelled++,b.controller.abort(),f(b));m()};return{acquire(v,b){return h||a.has(v)||[...l].some(T=>T.link===v)||a.size>=o||!b.range&&(a.size||r(b.charge)>0)?(c.refused++,i("refused"),Promise.resolve(null)):new Promise(T=>{let B=n();a.set(v,{link:v,key:b.key,size:b.size,charge:b.charge,range:b.range?{start:b.range.start,end:b.range.end}:null,queuedAt:B,deadline:B+250,resolve:T,waiting:a.size>0,active:!1}),m()})},finish:f,cancel:y,recheck:m,stop(){h=!0,y(),clearTimeout(u),u=null},snapshot:()=>({enabled:!0,...c,queued:a.size,reservedBytes:[...l].reduce((v,b)=>v+b.charge,0),limits:{waitMs:250,waiters:o,perLink:1}})}}var nl=2,zr="webrtc",Wi=16,Wn=3e4,sl=1e4,Ki=300,Kn=32*1024,Vi=Object.freeze({mode:"shadow",originFallbackMs:1500,maxPeerWaitMs:5e3,originReserveMs:2e3,sustainablePeerWait:!1,warmAhead:!1,startupBufferTarget:null,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}),il=32768,ol=500,al=2e3,I=()=>performance.now(),qr=n=>{let e=n?.loading?.first;return Date.now()-(Number.isFinite(e)&&e>0&&e<=I()?I()-e:0)},eo=n=>Array.from(new Uint8Array(n),e=>e.toString(16).padStart(2,"0")).join(""),$i=new TextEncoder;async function Nt(n){return eo(await globalThis.crypto.subtle.digest("SHA-256",n))}function Gi(n){return new URL(n,globalThis.location?.href).pathname}function ll(n){try{return new URL(n,globalThis.location?.href).origin}catch{return String(n)}}function _e(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 cl(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 Vn(n){return{p50:_e(n,.5),p90:_e(n,.9)}}function Ke(n,e){n.push(e),n.length>ol&&n.shift()}function Pt(){let n=globalThis.navigator?.connection;return!!(n&&(n.type==="cellular"||n.saveData))}var Fr=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"]}),Ve=n=>Math.min(Number.MAX_SAFE_INTEGER,n+1),Yi=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"]),Zi=Object.freeze(["payload","none","timeout","abort","abandoned","closed","busy","send-error"]),hl=15e3,ul=250,dl=50,Xi=Object.freeze(["presence","dialStart","offerBeforeSend","offerIncoming","answerIncoming","glareBeforeRollback","glareAfterRollback","answerBeforeSend","upload","refresh","other"]),fl=Object.freeze(["admission","not-held","not-serving","banned","session-allowance","peer-limit","rate-limit","reservation-refused","reservation-inactive"]);function Ji(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 pl(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 gl(){return eo(globalThis.crypto.getRandomValues(new Uint8Array(12)))}function Qi(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 bl(n={}){let e=new $n(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 $n=class{constructor(e){this.options={...Vi,...e},this.options.iceTransportPolicy===void 0&&(this.options.iceTransportPolicy=Vi.iceTransportPolicy),this.startedAt=Date.now(),this.transportStartedAt=I(),this.transportSequence=0,this.transportRecords=[],this.transportDropped=0,this.transportCounters=Object.fromEntries(Object.entries(Fr).map(([t,r])=>[t,Object.fromEntries(r.map(s=>[s,0]))])),this.transportConnections=new WeakMap,this.peerEligibilityRecords=[],this.peerEligibilityDropped=0,this.peerEligibilityCounters=Object.fromEntries(Yi.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(Zi.map(t=>[t,0])),this.uploadRefusalCounters=Object.fromEntries(fl.map(t=>[t,0])),this.admissionCallCounters=Object.fromEntries(Xi.map(t=>[t,0])),this.disabledReason=this.#n(),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 Lt,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={}}#n(){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"&&!Nr(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>il)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(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&&!we(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.#Je(t),this.options.warmAhead||this.options.startupBufferTarget){this.warmAhead=Fi({Loader:e.config.fLoader,steady:this.options.warmAhead,startupTarget:this.options.startupBufferTarget,startupCommit:this.options.startupBufferCommit,startupRecovery:i=>Math.max(this.options.originReserveMs,(_e(this.#W(i),.9)||0)*1.25+100),allowed:()=>this.#p()&&e.media?.paused!==!0&&!Pt(),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 at(u=>this.options.getCommitment(i,{signal:u}),o,1e3);if(o.aborted||this.stopped)return null;let c=u=>!this.stopped&&this.#ce(l,{streamEvent:this.options.streamEvent,swarmId:this.options.swarmId,key:a,context:u,maxSegmentBytes:this.options.maxSegmentBytes,delegation:this.options.delegation,revokedDelegationIds:this.options.revokedDelegationIds,delegationRevocations:this.options.delegationRevocations}),h=c(i);return h&&h.size<=this.options.maxHeldBytes?{...h,key:a,current:u=>{let p=c(u);return!!(p&&p.size===h.size&&p.sha256===h.sha256)}}:null},verify:async(i,o,a,l)=>o instanceof ArrayBuffer&&o.byteLength===i.size&&!l.aborted&&await Nt(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,(_e(this.#W(i),.9)||0)*1.25+100);for(let c=0;ca)return Math.min(25,Math.max(0,(h-a)*1e3-l))}}catch{}return 0},onVerified:(i,o)=>(this.#rt(i.key),this.#T(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(al,r);this.coreRelease=r,this.coreWait=s.then(()=>{clearTimeout(i),this.timers.delete(i),this.coreWait=null,this.coreRelease=null}),this.#r("core",()=>this.#it().finally(r))}this.#r("start",()=>this.#lt()),typeof this.options.onMetrics=="function"&&this.#k(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,h]of l)h?Object.defineProperty(o,c,h):delete o[c]}},e.trigger=this.withheldTrigger)}updateTicket(e){return this.stopped||this.disabledReason||!this.#G()||!we(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.#F(),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.#se(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=Ve(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,h=g=>{let f=g;try{f??=r()}catch{}let m=y=>{try{let v=f?.[y];return Number.isSafeInteger(v)&&v>=0?v:null}catch{return null}};return{loaderLoadedBytes:m("loaded"),loaderTotalBytes:m("total")}},u=(g,f)=>this.#e({k:g,load:e,leg:t,at:this.#s(),ms:Math.round(I()-s),ranged:!1,...f});return u("originStart",{}),{progress:(g,f,m)=>{if(m){c||(c=!0,u("originCallback",{phase:"progress",outcome:null,stale:!0}));return}a||f!==!0||(a=!0,u("originProgress",{stale:!1,...h(g)}))},abortRequest:g=>{o||l||(l=!0,u("originAbortRequest",{reason:g,...h()}))},terminal:(g,f=null,m,y=!1)=>p(g,f,m,y)};function p(g,f,m,y){if(o){c||(c=!0,u("originCallback",{phase:"terminal",outcome:g,stale:!0}));return}o=!0;let v=y?{loaderLoadedBytes:null,loaderTotalBytes:null}:h(m);u("origin",{at:Math.floor(s)-i,outcome:g,bytes:Number.isSafeInteger(f)&&f>=0?f:null,stale:y,...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:nl,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:_e(this.signallingSamples,.5),p90Ms:_e(this.signallingSamples,.9),clock:{...this.session?this.session.clockDiagnostics():{aheadRejected:null,staleRejected:null,maxAheadSeconds:null,signalSamples:null,signalAgeMedianSeconds:null},origin:Xn(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:_e(this.peerLatencySamples,.5),peerLatencyP90Ms:_e(this.peerLatencySamples,.9),originLatencyMedianMs:_e(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.#L(),...this.multiHolder,originRangeOutcomes:{...this.originRangeOutcomes},timings:{durationMs:Vn(this.multiHolderTimings.map(o=>o[0])),slowestRequestMs:Vn(this.multiHolderTimings.map(o=>o[1])),requests:Vn(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)}#r(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.#r("timer",t)},Math.max(0,e));return this.timers.add(r),r}#k(e,t,r){let s=()=>{let i=e*t*(Math.random()*2-1);this.#h(e+i,()=>{try{r()}finally{s()}})};s()}#M(e,t){try{let r=Zn(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.#ze(s,a);if(t.#Y(s),t.options.peerSupplyHint&&t.#r("player-hint",()=>t.#B(s,l)),t.stopped||!s.frag||s.frag.sn==="initSegment"||s.part&&!t.options.swarmParts||!t.options.serveOnCellular&&Pt())return this.inner.load(s,i,o);if(l===0&&t.options.zeroBudgetPeerRace&&!this.hlsConfig.progressive&&t.#L()&&t.#l()){let S=new Map([...t.links.values()].filter(L=>t.#K(L,s)&&L.supportsRanges&&(t.remoteFraming.get(L.pubkey)??1)>=2&&!t.banned.has(L.pubkey)&&(L.have.size||t.options.lateHaveRace)).map(L=>[L,new Set(L.have)]));if(S.size)return this.loadCachedRace(s,i,o,a,S)}let c=i?.loadPolicy?.maxLoadTimeMs??i?.timeout;if(l===0&&t.options.latePeerRace&&!this.hlsConfig.progressive&&Ae(s)&&Number.isFinite(c)&&c>0&&t.#l())return this.loadLatePeerRace(s,i,o,a,c);let h=new AbortController,u={};this.active=u;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",y)};this.cancel=()=>{let S=this.active===u;return this.active=null,m(),h.abort(),S};let y=()=>{if(this.active!==u)return;this.active=null,this.pendingCallbacks=null,m(),h.abort(),t.counters.originFallbacks+=1,this.inner.stats.loading.start=0;let S=I(),L=!1,U=null,C=t.#C(s);C.then(w=>{!L&&!t.stopped&&(U=w,this.releaseFetch=t.#Z(w))}).catch(()=>{});let F=()=>L?!1:(L=!0,this.releaseFetch?.(),this.releaseFetch=null,!0),O=this.cancel;this.cancel=()=>(F(),O());let d=this.originTrace=t.#c(f,"fallback",()=>this.inner.stats);this.inner.load(s,i,{...o,onError:(...w)=>{d?.terminal("error",null,void 0,d!==this.originTrace),F(),o.onError?.(...w)},onTimeout:(...w)=>{d?.terminal("timeout",null,w[0],d!==this.originTrace),F(),o.onTimeout?.(...w)},onAbort:(...w)=>{d?.terminal("abort",null,w[0],d!==this.originTrace),F(),o.onAbort?.(...w)},onSuccess:(w,A,x,R)=>{if(L)return;let P=qr(A),{copy:N,size:M}=t.#S(w,s);if(!L&&(U&&N&&t.#T(U,new Uint8Array(N)),!!F())){if(this.pendingCallbacks=null,d?.terminal("payload",M||null,A,d!==this.originTrace),Ke(t.originLatencySamples,I()-S),t.#X(t.renditionOriginSamples,s,I()-S),t.options.peerSupplyHint&&M){let H=t.#v(s);!t.hintSizes.has(H)&&t.hintSizes.size>=16&&t.hintSizes.delete(t.hintSizes.keys().next().value),t.hintSizes.set(H,M);let D=I()-S;D>0&&Ke(t.hintOriginRates,M/D)}o.onSuccess(w,A,x,R),t.#M(R,P),M&&!t.stopped&&t.#r("peer-first-origin",async()=>{if(t.counters.originLoaded+=1,t.counters.bytesFromOrigin+=M,!U){let H=await C;N&&!t.stopped&&t.#T(H,new Uint8Array(N))}})}}})};if(l===0)return f=t.#i(s,0,0,a),t.#E(s,l,"no-budget",null,a),y();let v=()=>{$.onDeadline?.()||($.expired=!0,y())};g=setTimeout(v,l),t.lifecycle.signal.addEventListener("abort",y,{once:!0});let b=Math.max(t.options.originFallbackMs,t.options.maxPeerWaitMs),T=Math.max(l,Math.min(b,a.uncappedMs??l,a.sustainableMs??1/0));f=t.#i(s,l,T,a);let B={Loader:e,config:this.hlsConfig,loaderConfig:i},$={deadline:p+l,limit:p+T,originReserveMs:a.originReserveMs??t.options.originReserveMs,expired:!1,onDeadline:null,origin:B,extend:S=>{let L=Math.min($.limit,S);return this.active!==u||L<=$.deadline?!1:($.deadline=L,clearTimeout(g),g=setTimeout(v,Math.max(0,L-I())),!0)}};t.#ae(s,h.signal,$,l,a).then(S=>{if(!(this.active!==u||h.signal.aborted||t.stopped)){if(S&&!S.multi&&I()>=$.deadline&&t.#N(S.demand),!S||I()>=$.deadline&&!S.multi)return y();this.active=null,this.pendingCallbacks=null,m(),t.#O(this,S,s,o,p)}}).catch(S=>{this.active===u&&(t.#o("peer-first",S),y())})}loadCachedRace(s,i,o,a,l){let c=t.#i(s,0,t.options.maxPeerWaitMs,a),h={},u=new AbortController,p=I(),g=!0,f=!1,m=null,y,v;this.active=h,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 b=()=>{clearTimeout(v),t.lifecycle.signal.removeEventListener("abort",b),t.cachedRaces.delete(u),u.abort()};t.cachedRaces.add(u),t.lifecycle.signal.addEventListener("abort",b,{once:!0}),this.cancel=()=>{let S=g&&this.active===h;g=!1,this.active=null,b();try{this.inner.abort()}catch{}return S};let T=()=>!g||this.active!==h?!1:(g=!1,this.active=null,this.pendingCallbacks=null,b(),this.releaseFetch?.(),this.releaseFetch=null,!0);v=setTimeout(b,t.options.maxPeerWaitMs),t.counters.originFallbacks+=1,t.#E(s,0,"no-budget",null,a);let B=this.originTrace=t.#c(c,"cached",()=>this.inner.stats);try{this.inner.load(s,i,{...o,onProgress:(...S)=>{if(!g||this.active!==h){B?.progress(void 0,null,!0);return}let L=S[2]?.byteLength>0;L&&(f=!0,b()),B?.progress(S[0],L,!1),o.onProgress?.(...S)},onError:(...S)=>{B?.terminal("error",null,void 0,!g||this.active!==h),T()&&o.onError?.(...S)},onTimeout:(...S)=>{B?.terminal("timeout",null,S[0],!g||this.active!==h),T()&&o.onTimeout?.(...S)},onAbort:(...S)=>{B?.terminal("abort",null,S[0],!g||this.active!==h),T()&&o.onAbort?.(...S)},onSuccess:(S,L,U,C)=>{if((!g||this.active!==h)&&B?.terminal("payload",null,void 0,!0),!g||this.active!==h)return;let F=qr(L),{copy:O,size:d}=t.#S(S,s);!g||this.active!==h||(m&&O&&t.#T(m,new Uint8Array(O)),T()&&(B?.terminal("payload",d||null,L),Ke(t.originLatencySamples,I()-p),t.#X(t.renditionOriginSamples,s,I()-p),o.onSuccess(S,L,U,C),t.#M(C,F),d&&!t.stopped&&t.#r("cached-race-origin",async()=>{if(t.counters.originLoaded+=1,t.counters.bytesFromOrigin+=d,!m){let w=await(y??t.#C(s));O&&!t.stopped&&t.#T(w,new Uint8Array(O))}})))}})}catch(S){throw T(),S}if(!g)return;y=t.#C(s),y.then(S=>{g&&!t.stopped&&(m=S,this.releaseFetch=t.#Z(S))}).catch(()=>{});let $={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,u.signal,$,0,a).then(S=>{if(!(!S||!g||f||this.active!==h||u.signal.aborted||t.stopped||I()>=$.limit)){g=!1,this.active=null,this.pendingCallbacks=null,b(),this.releaseFetch?.(),this.releaseFetch=null,B?.abortRequest("peer-won");try{this.inner.abort()}catch{}t.counters.zeroBudgetPeerRaceWins+=1,t.#O(this,S,s,o,p)}}).catch(S=>{g&&!u.signal.aborted&&!t.stopped&&t.#o("cached-race",S)}).finally(b)}loadLatePeerRace(s,i,o,a,l){let c=t.#i(s,0,l,a),h={},u=new AbortController,p=I(),g=!0,f=!1,m=null,y;this.active=h,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===h&&!t.stopped,b=B=>!g||this.active!==h?!1:(g=!1,this.active=null,this.pendingCallbacks=null,y?.close(B),this.releaseFetch?.(),this.releaseFetch=null,!0);this.cancel=()=>{let B=g&&this.active===h;g=!1,this.active=null,y?.close("caller-abort"),this.releaseFetch?.(),this.releaseFetch=null;try{this.inner.abort()}catch{}return B};let T;y=t.#w({context:s,controller:u,entryAt:p,parentDeadline:p+l,current:v,arm:(B,$)=>(t.options.traceRequests&&t.traceLoads.set(B,c),t.#ae(B,u.signal,$,0,a).then(S=>{if(!S||!v()||u.signal.aborted||I()>=$.limit||!y.valid()||typeof $.revalidateAuthority!="function"||!$.revalidateAuthority())return!1;g=!1,this.active=null,this.pendingCallbacks=null,y.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,S,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:(...B)=>{if(!g||this.active!==h){T?.progress(void 0,null,!0);return}let $=B[2]?.byteLength>0;$&&(f=!0,y?.close("origin-progress")),T?.progress(B[0],$,!1),o.onProgress?.(...B)},onError:(...B)=>{T?.terminal("error",null,void 0,!g||this.active!==h),b("origin-error")&&o.onError?.(...B)},onTimeout:(...B)=>{T?.terminal("timeout",null,B[0],!g||this.active!==h),b("origin-timeout")&&o.onTimeout?.(...B)},onAbort:(...B)=>{T?.terminal("abort",null,B[0],!g||this.active!==h),b("origin-abort")&&o.onAbort?.(...B)},onSuccess:(B,$,S,L)=>{if((!g||this.active!==h)&&T?.terminal("payload",null,void 0,!0),!g||this.active!==h)return;let U=qr($),{copy:C,size:F}=t.#S(B,s);!g||this.active!==h||(m&&C&&t.#T(m,new Uint8Array(C)),b("origin-success")&&(T?.terminal("payload",F||null,$),Ke(t.originLatencySamples,I()-p),t.#X(t.renditionOriginSamples,s,I()-p),o.onSuccess(B,$,S,L),t.#M(L,U),F&&!t.stopped&&t.#r("late-race-origin",async()=>{if(t.counters.originLoaded++,t.counters.bytesFromOrigin+=F,!m){let O=await(y?.keyPromise??t.#C(s));C&&!t.stopped&&t.#T(O,new Uint8Array(C))}})))}})}catch(B){throw b("origin-throw"),B}g&&y?.keyPromise.then(B=>{g&&this.active===h&&!t.stopped&&(m=B,this.releaseFetch=t.#Z(B))}).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?.[Te]?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)}#A(){for(let e of[...this.latePeerOwners.values()])e.refresh()}#w(e){let t=Ae(e.context);if(!t||!this.#l())return null;let r=e.context[Te],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},h=(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),u=()=>{let p=c();return!p||!Number.isFinite(p.at)||Ae(p.context)?.key!==t.key?null:r?{...p.context,[Te]:r}:p.context};o.valid=()=>!o.closed&&e.current()&&!this.stopped&&o.generation===this.latePeerGeneration&&o.streamId===this.options.streamEvent?.id&&u()!==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=u();if(!g||i?.paused||i?.ended)return o.close("context-or-playback");if(o.windowEnd===null){let y=p.role==="startup-buffer-dependency";o.genuineAt=y?null:p.at,o.dependencyAt=y?s:null,o.dependencyDeadline=y?p.deadline:null,o.windowEnd=Math.min(e.parentDeadline,y?p.deadline:1/0,(y?s:p.at)+Math.min(4e3,this.options.lateWindowMs)),y&&p.signal.addEventListener("abort",()=>o.close("startup-buffer-ended"),{once:!0,signal:a.signal}),this.#f(o,"entered",y?"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.#L())return;let f=[...this.links.values()].filter(y=>h(y,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 y=await Promise.all(f.map(async S=>{if(!this.options.admit)return S;let L=this.admissionChecks.get(S.pubkey)?.ticket??this.admitted.get(S.pubkey)?.ticket,U=!1;try{U=await at(()=>this.#x(S.pubkey,L,"other"),o.controller.signal,Math.max(0,Math.min(this.options.admissionTimeoutMs,m-I())))===!0}catch{}return!U&&!o.closed&&S.close("admission"),U?S:null}));if(o.closed)return;let v=u();if(!e.current()||!v||I()>=m||o.generation!==this.latePeerGeneration)return o.close("inactive-after-admission");let b=y.filter(S=>S&&h(S,v));if(!b.length)return o.close("admission-or-have-refused","refused");o.validatedPeers=new Map(b.map(S=>[S,this.admitted.get(S.pubkey)?.ticket]));let T=Ae(v)?.context;if(!T||!o.valid())return o.close("context-after-admission");let B={deadline:m,limit:m,originReserveMs:0,expired:!1,onDeadline:null,knownKey:o.key,cachedOnly:new Map(b.map(S=>[S,new Set([o.key])])),lateHaveRace:!1,peerOnly:!0,extend:()=>!1,currentValid:o.valid,revalidateAuthority:!0};!await e.arm(T,B)&&!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.#F(),this.firstPeerSegmentAtMs===null&&(this.firstPeerSegmentAtMs=Date.now()-this.startedAt),Ke(this.peerLatencySamples,o-i),p.frag&&this.peerFragments.add(p.frag)}},h=()=>{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{}}},u=p=>{c(p),h()};r[Te]?Object.assign(r[Te],{peerBytes:l,accept:u,commit:c,notify:h}):u(r),!r[Te]&&this.#p()&&!this.held.has(t.key)&&this.#T(t.key,t.bytes.slice()),s.onSuccess({url:r.url,data:t.bytes.buffer,code:200},e.peerStats,r,null)}async#B(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(h=>h.sn===e.frag.sn&&h.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}`,h=a?await this.#C(a):null;if(this.stopped||r!==this.hintGeneration)return null;let u=a&&this.discovery.contexts.get(a.frag.type||"main"),p=h?[...this.links.values()].filter(T=>this.#P(T)&&T.have.has(h)&&T.supportsRanges===!0&&(this.remoteFraming.get(T.pubkey)??1)>=2&&!this.banned.has(T.pubkey)&&!(u?.rendition===c&&this.discovery.stale(u,T.pubkey))).map((T,B)=>{let $=this.peerSelection.summary(T).throughputBytesPerSecond;return[B+1,null,$?$/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),y=_e(this.renditionOriginSamples.get(c)||[],.5),v={rendition:c,size:m,peers:p,origin:[null,m&&y?m/y:_e(this.hintOriginRates,.5)],sharedFirstByteMs:this.peerSelection.firstByteMs(),sharedRate:this.peerSelection.rate(),availableMs:t,maxHolders:this.options.maxHoldersPerObject},b=this.core?.playerHint(v);return b&&this.options.traceRequests&&this.#e({k:"playerHint",at:this.#s(),input:v,out:b}),b?{...b,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=_t(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=Ae(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,h)=>(parseInt(c,16)^parseInt(e[h],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)}}}#ze(e,t){if(e?.[Te])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=_e(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,(_e(this.#W(e),.9)||0)*1.25+100),a,l,c,h=(a=e?.part?.start)??e?.frag?.start,u=Number.isFinite(h)&&h>r.currentTime?Math.min(l=r.buffered.end(i),h):l=r.buffered.end(i),p=Math.max(0,(u-(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(u),fragmentStart:f(h),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||Gi)(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 Nt($i.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}#Fe({key:e,rendition:t,context:r}){let s=l=>l.sort((c,h)=>c-h).slice(0,8),i=[],o=[],a=[];for(let l of this.links.values()){let c=this.#U(l.pubkey);this.#q(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(h=>this.#q(h,i));if(t&&![...this.links.values()].some(h=>h.have.has(s))){for(let h of a)this.discovery.holderMiss(o,h.pubkey,s);return}let l=a.filter(h=>e.asked.has(h.pubkey)||r.includes(h.pubkey)),c=[];for(let h of l)this.discovery.holderMiss(o,h.pubkey,s)&&(this.discovery.counters.heldMiss++,c.push(this.#U(h.pubkey)));c.length&&e.row?.heldMissHolders&&(e.row.heldMissHolders=c.sort((h,u)=>h-u).slice(0,8))}catch{}}}#je(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(!Yi.includes(r))return;let h=m=>Number.isSafeInteger(m)&&m>=0?m:null,u=null,p=null;try{u=h(e?.frag?.cc)}catch{}try{p=h(e?.frag?.level)}catch{}let g=I()-this.transportStartedAt,f={atMs:Number.isFinite(g)?Math.max(0,Math.round(g)):0,cc:u,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.#Fe(a))}catch{Object.assign(f,{holders:null,haveHolders:null,staleHolders:null,heldMissHolders:null})}a.row=f}this.peerEligibilityCounters[r]=Ve(this.peerEligibilityCounters[r]),this.peerEligibilityRecords.length===64&&(this.peerEligibilityRecords.shift(),this.peerEligibilityDropped=Ve(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)||[];Ke(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}}#We(e,t,r,s){if(!(t>0)||!Number.isFinite(t)||rWi&&o.firstBytes.shift();let l=s-r;l>=Ki&&i>=Kn&&(o.flows.push({value:Math.min(1e6,i/l),flowMs:l,at:a}),o.flows.length>Wi&&o.flows.shift())}#pe(e,t,r=null){if(!e||e.closed||!Number.isSafeInteger(t)||t<=0)return;let s=this.#oe(e);Number.isFinite(r)&&(s.flows=s.flows.filter(i=>i.at>=r)),s.usefulAt=I()}#Ve(e,t,r){let s=this.#oe(e),i=I();s.firstBytes=s.firstBytes.filter(u=>i-u.at<=Wn),s.flows=s.flows.filter(u=>i-u.at<=Wn);let o=s.firstBytes.reduce((u,p)=>u===null?p.value:(u+p.value)/2,null),a=s.flows.filter(u=>u.flowMs>=(o??0)*3),l=cl((a.length>=2?a:s.flows).map(u=>u.value),.75),c=l!==null&&(o??0)+r/l<=t,h=l===null&&(o??0)=sl)return{state:s,firstByteMs:null,rate:null,refresh:!0};if(l===null)return null}return{state:s,firstByteMs:o,rate:l,refresh:!1}}#$e(e,t){let r=_e(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>=hl?"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)}#J(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 O=w=>[...r.cachedOnly].filter(([A,x])=>(!w||x.has(c))&&A.have.has(c)&&this.links.get(A.pubkey)===A&&this.#K(A,e)&&!this.banned.has(A.pubkey)&&A.supportsRanges===!0&&(this.remoteFraming.get(A.pubkey)??1)>=2).map(([A])=>A),d=O(!0);if(!d.length&&r.lateHaveRace){for(d=O(!1);!d.length&&!t.aborted&&!this.stopped&&I()0}if(t.aborted||this.stopped||I()>=r.limit||(r.cachedHolders=new Set(d),!r.cachedHolders.size||!this.#L()))return null;this.counters.zeroBudgetPeerRaces+=1}let h=this.#v(e),u=l?.rendition===h&&this.discovery.contexts.get(l.mediaType)===l?l:null;if(u&&!r.cachedOnly){this.discovery.demand(l.mediaType,h,c);let O=this.discovery.counters.checks;this.#te();try{this.#je(u,O)}catch{}}let p={key:c,rendition:h,context:u,recorded:!1,asked:new Set,row:null},g=![...this.links.values()].some(O=>O.have.has(c));if(g&&!this.#I(c,h,e))return this.#E(e,s,"no-have-no-wait",!1,i,void 0,p,!1,o),null;let f=this.renditionSizes.get(h),m=g?this.#$e(c,h):0,y=f?this.peerSelection.projectMs(f):null,v=!g&&this.#L()&&[...this.links.values()].some(O=>this.#K(O,e)&&O.supportsRanges===!0&&O.have.has(c)&&!this.banned.has(O.pubkey)&&(this.remoteFraming.get(O.pubkey)??1)>=2&&!(u&&this.discovery.stale(u,O.pubkey))),b=r.cachedOnly||v?"unknown":this.#ge(y,m,r),T=null;if(b==="late"&&!g&&this.#be(p,r)&&(T=this.#J("entry",y,m,r),b="stretch"),b==="late")return this.#E(e,s,"projected-late",!g,i,this.#J("entry",y,m,r),p,!1,o),this.#N(p,{everyServing:!0}),this.counters.peerProjectedLate+=1,null;this.#me(b,m+y,r),g&&(this.#E(e,s,"no-have-wait",!1,i,void 0,p,!1,o),this.counters.coordinatedWaits+=1);let B=r.deadline-I();if(t.aborted||this.stopped||B<=0)return null;this.counters.commitmentRequests+=1;let $=at(O=>{if(t.aborted||this.stopped||I()>=r.deadline)throw new Error("Commitment load no longer active.");return this.options.getCommitment(e,{signal:O})},t,B).then(O=>({ok:!0,event:O}),()=>({ok:!1}));if(g){for(;!t.aborted&&!this.stopped&&I()d.have.has(c));){if(!this.#I(c,h,e))return this.#E(e,s,"wait-no-longer-eligible",!1,i,void 0,p,!1,o),null;await this.#Q(c,Math.min(100,r.deadline-I()),t)}let O=t.aborted||this.stopped;if(O||I()>=r.deadline)return this.#E(e,s,O?"wait-aborted":"wait-expired",null,i,void 0,p,!1,o),(!O||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 S,L;try{let O=await $;if(!O.ok)throw new Error("Commitment unavailable.");L=O.event,S=this.#ce(O.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(!S)return this.counters.commitmentRejected+=1,null;if(r.currentValid&&!r.currentValid()||(r.revalidateAuthority===!0&&(r.revalidateAuthority=()=>!!this.#ce(L,{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&&S.v!==3)return null;if(!this.renditionSizes.has(h)&&this.renditionSizes.size>=16&&this.renditionSizes.delete(this.renditionSizes.keys().next().value),this.renditionSizes.set(h,S.size),S.v===3&&this.options.multiHolder){let O=await this.#Ze(e,t,r,c,S,l,o);if(O!==void 0)return O&&g&&(this.counters.coordinatedPeerLoads+=1),O&&{...O,holderContext:u}}if(r.cachedOnly)return null;let U=this.peerSelection.projectMs(S.size),C=this.#ge(U,0,r);if(C==="late"&&!g&&(T!==null||this.#be(p,r))&&(T=this.#J("commitment",U,0,r),C="stretch",p.row&&(p.row.projection={...T},p.row.trial=!0)),C==="late")return this.#E(e,s,"projected-late",!0,i,this.#J("commitment",U,0,r),p,!1,o),this.counters.peerProjectedLate+=1,null;this.#me(C,U,r);let F=new Set;for(;!t.aborted&&!this.stopped&&I()O||(d??0)>O)return this.counters.peerSkippedLate+=1,null;let w=(V,re)=>this.peerSelection.estimate(V,S.size)===null||this.peerSelection.estimate(V,S.size)*1.25+25<=re,A=T&&F.size===0?this.#ye(c,p.context):null;A&&this.peerSelection.markSelected(A);let x=A??this.peerSelection.select([...this.links.values()].filter(V=>this.#P(V)),c,F,S.size,O);if(!x){if(![...this.links.values()].some(V=>!V.closed&&!F.has(V.pubkey)&&V.have.has(c)&&w(V,O)))return this.counters.peerNoFit+=1,this.#N(p,{unfit:[...this.links.values()].filter(V=>!V.closed&&!F.has(V.pubkey)&&V.have.has(c)&&!w(V,O)).map(V=>V.pubkey)}),null;await this.#Q(c,Math.min(100,r.deadline-I()),t);continue}F.add(x.pubkey),p.asked.add(x.pubkey),A&&(this.counters.peerUntestedTrial+=1);let R=this.peerSelection.estimate(x,S.size);R!==null&&r.extend(I()+R*1.25+25)&&(this.counters.peerWaitExtended+=1);let P=I(),N=r.deadline-I(),M=[...this.links.values()].filter(V=>this.#P(V)&&!F.has(V.pubkey)&&V.have.has(c)&&w(V,N)).length,H=N-Math.min(2,M)*25,D=R===null?Math.min(N,Math.max(25,H)):Math.min(N,Math.max(25,N/Math.min(3,M+1),R*1.25+25)),q=this.#Xe(t,P,S.size,r,d),ee;try{ee=await x.request(c,Math.max(1,D),{signal:q.signal,expectedSize:S.size,onProgress:q.progress,onResult:V=>this.#we(e,x,N,V,null,o)})}finally{q.done()}if(this.peerSelection.observe(q.observation()),q.abandoned)return this.#R(x,I()-P),this.counters.peerAbandoned+=1,this.#N(p),null;if(!ee||t.aborted||this.stopped){!t.aborted&&!this.stopped&&this.#R(x,I()-P);continue}let j=await Nt(ee);if(this.stopped)return null;if(ee.byteLength!==S.size||j!==S.sha256){if(this.#R(x,I()-P),this.counters.peerCorrupt+=1,this.banned.add(x.pubkey),p.asked.delete(x.pubkey),x.close("integrity"),t.aborted)return r.expired&&this.#N(p),null;continue}return t.aborted?(r.expired&&this.#N(p),null):S.expiresAt<=Math.floor(Date.now()/1e3)?null:(this.#R(x,I()-P,ee.byteLength),g&&(this.counters.coordinatedPeerLoads+=1),A&&(this.counters.peerUntestedTrialLoaded+=1),{key:c,bytes:ee,discoveryContext:l,holderContext:u,pubkey:x.pubkey,demand:p,connection:x.pc})}return!this.stopped&&(!t.aborted||r.expired)&&this.#N(p),null}#Ge(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?.[Te]&&!e.closed&&this.peerLeases.has(e))}#Ye(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#Ze(e,t,r,s,i,o,a){if(r.currentValid&&!r.currentValid())return null;let l=this.options.transferWorkerUrl!==void 0;if(l&&(!this.#L()||this.transferWorkerState!=="ready"))return null;if(!this.#L()||!Array.isArray(i.pieces))return;let c=ll(e.url);if(!r.peerOnly&&this.originsWithoutRanges.has(c))return l?null:void 0;let h=b=>this.links.get(b.pubkey)===b&&!b.closed&&b.supportsRanges===!0&&b.have.has(s)&&!this.banned.has(b.pubkey)&&(this.remoteFraming.get(b.pubkey)??1)>=2&&(!r.cachedHolders||r.cachedHolders.has(b)),u=[...this.links.values()].filter(b=>h(b)&&this.#K(b,e)),p=()=>u.filter(b=>h(b)&&this.#P(b)),g=p();if(!g.length&&e?.[Te]&&u.some(b=>this.peerLeases.has(b))&&(await this.#Ye(u,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(b=>[b,this.#Ve(b,Math.max(0,r.limit-I()),i.pieceSize)]).filter(([,b])=>b!==null));if(!f.size)return this.counters.peerNoFit+=1,null;let m=[...f.keys()],y={};for(let b of m)this.peerLeases.set(b,y);this.peerAdmission.claims+=m.length;let v=()=>{t.removeEventListener("abort",v);for(let b of m)this.peerLeases.get(b)===y&&this.peerLeases.delete(b);for(let b of[...this.peerLeaseWaiters])this.#h(0,b);this.latePeerOwners.size&&this.#h(0,()=>this.#A())};t.addEventListener("abort",v,{once:!0});try{let b=new Map(m.map(x=>[this.#Ge(x),x])),T=Math.floor(r.limit),B=r.peerOnly?r.limit:r.limit+r.originReserveMs,$={size:i.size,sha256:i.sha256,pieces:i.pieces,deadline:T,maxHolders:this.options.maxHoldersPerObject,originReserveMs:0,...r.peerOnly?{peerOnly:!0}:{}},S;try{S=l?await this.transferWorker.transfer($,{signal:t}):this.core.transfer($)}catch{return null}if(this.stopped||t.aborted||l&&I()>=T||r.currentValid&&!r.currentValid()||typeof r.revalidateAuthority=="function"&&!r.revalidateAuthority()||m.some(x=>!h(x)||x.busy||this.peerLeases.get(x)!==y))return S?.free(),null;if(!S)return l||r.peerOnly?null:void 0;this.multiHolder.transfers+=1;let L=a,U=this.traceBase,C=(x,R,P)=>{let N=Math.floor(I()),M=D=>(this.options.traceRequests&&this.#e({k:"xfer",load:L,op:x,at:N-U,...R,out:D&&{c:D.commands.map(({t:q,peer:ee,p:j})=>({t:q,...ee!==void 0?{peer:ee}:{},...j?{p:[...j]}:{}})),next:D.next===null?null:D.next-U,late:D.late,finished:D.finished}}),D),H=P(N);return H?.then?H.then(M):M(H)};r.extend(r.limit);let F=i.pieceSize,O=({start:x,end:R})=>[x*F,Math.min(R*F,i.size)],d=[...b].map(([x,R])=>[x,f.get(R).firstByteMs,f.get(R).rate]),w=r.peerOnly?null:_e(this.#W(e),.5),A=r.peerOnly?null:[0,w?i.size/w:null];return await new Promise(x=>{let R=new Map,P=new Set,N=new WeakSet,M=new Map,H=new Map,D=!1,q=null,ee=null,j=null,V=0,re=0,ae=(W,ve)=>{let ie=W?.verified==null?0:Math.max(0,W.verified-re);return W?.verified!=null&&(re=Math.max(re,W.verified)),this.multiHolder.unusedBytes+=ve-ie,ie},ge=I(),ne=0,pe=0,Q=W=>(W!==null&&(clearTimeout(W),this.timers.delete(W)),null),me=W=>{if(!D){D=!0,q=Q(q),ee=Q(ee);for(let ve of[...R.values(),...P])ve.abort();j?.(),r.onDeadline=null,t.removeEventListener("abort",et),S.free(),x(W)}},et=()=>me(null);t.addEventListener("abort",et,{once:!0});let Ie=(W,ve,ie,Be=ft)=>{if(D)return;let E=k=>{if(!D){if(r.currentValid&&!r.currentValid()||(l||r.peerOnly)&&I()>=B)return me(null);k?Be(k):me(null)}};try{let k=C(W,ve,ie);k?.then?k.then(E,()=>me(null)):E(k)}catch{me(null)}},jr=(W,ve)=>{if(W.t==="request"){let ie=b.get(W.peer),Be=new AbortController;R.set(W.peer,Be);let[E,k]=O(W.range),z=I(),Z=Math.max(1,T-z),_=null,K=-1/0;pe+=1,f.get(ie).refresh&&(f.get(ie).refreshStartedAt??=I(),f.get(ie).state.probeAt=I());let J=X=>{let G=I();D||R.get(W.peer)!==Be||G-KS.progress(te,W.peer,X)))};ie.request(s,Z,{signal:Be.signal,expectedSize:k-E,onProgress:J,range:{start:W.range.start,end:W.range.end,objectSize:i.size},onResult:X=>{_=X,this.#we(e,ie,Z,X,W.range,a)}}).then(X=>{R.get(W.peer)===Be&&R.delete(W.peer),ne=Math.max(ne,I()-z),!D&&(_?.firstByteMs!==null&&_?.elapsedMs!==null&&_?.receivedBytes&&this.peerSelection.observe({firstByteMs:_.firstByteMs,bytes:_.receivedBytes,flowMs:_.elapsedMs-_.firstByteMs}),X?(this.#R(ie,I()-z,X.byteLength),Ie("delivered",{source:W.peer,p:[W.range.start,W.range.end],bytes:X.byteLength},G=>S.delivered(G,W.peer,W.range,X),G=>{let te=ae(G,X.byteLength);this.multiHolder.peerBytes+=te,te>0&&M.set(ie.pc,(M.get(ie.pc)??0)+te);let xe=_?.elapsedMs-_?.firstByteMs;te>0&&f.get(ie).refresh&&_?.receivedBytes>=Kn&&Number.isFinite(xe)&&xe>=0&&xeS.failed(G,W.peer))))},()=>{D||Ie("failed",{source:W.peer},X=>S.failed(X,W.peer))})}else if(W.t==="origin"){if(r.peerOnly){this.multiHolder.failed+=1,me(null);return}j??=this.#Z(s);let ie=new AbortController,[Be,E]=O(W.range),k=I(),z=null,Z=K=>{z=K,this.originRangeOutcomes[K.outcome]=Ve(this.originRangeOutcomes[K.outcome])};P.add(ie),this.multiHolder.originRanges+=1;let _=()=>{this.originsWithoutRanges.has(c)||(this.originsWithoutRanges.add(c),this.multiHolder.originRangesIgnored+=1)};(r.origin?.Loader?Ui(r.origin,e,Be,E,{signal:ie.signal,onIgnored:_,onResult:Z}):zi(e,Be,E,{signal:ie.signal,onIgnored:_,onResult:Z})).then(K=>{if(P.delete(ie),this.options.traceRequests&&this.#e({k:"origin",load:L,at:this.#s(k),ms:Math.round(I()-k),ranged:!0,range:[W.range.start,W.range.end],outcome:z?.outcome??(K?"payload":D?"abort":"none"),httpStatus:z?.httpStatus??null,bytes:K?.byteLength??null}),D)return;let J=[W.range.start,W.range.end];if(!K)return Ie("failed",{source:"origin"},X=>S.failed(X,"origin"));this.#We(e,I()-k,K.byteLength,i.size),this.counters.bytesFromOrigin+=K.byteLength,Ie("delivered",{source:"origin",p:J,bytes:K.byteLength},X=>S.delivered(X,"origin",W.range,K),X=>{let G=ae(X,K.byteLength);this.multiHolder.originBytes+=G,V+=G,ft(X)})})}else if(W.t==="cancel"||W.t==="abandon"){let ie=R.get(W.peer);W.t==="abandon"&&(this.multiHolder.abandoned+=1,ie&&N.add(ie)),ie?.abort(W.t==="abandon"?ot.ABANDON_REASON:void 0)}else if(W.t==="ban"){let ie=b.get(W.peer);this.multiHolder.bans+=1,this.counters.peerCorrupt+=1,this.banned.add(ie.pubkey),ie.close("integrity")}else if(W.t==="deliver"){this.multiHolder.delivered+=1,this.multiHolderTimings.push([I()-ge,ne,pe]),this.multiHolderTimings.length>128&&this.multiHolderTimings.shift();let ie=ve.bytes.byteOffset===0&&ve.bytes.byteLength===ve.bytes.buffer.byteLength?ve.bytes:ve.bytes.slice();me(i.expiresAt<=Math.floor(Date.now()/1e3)?null:{key:s,bytes:ie,discoveryContext:o,multi:!0,peerBytes:Math.max(0,i.size-V),contributions:[...M].map(([Be,E])=>({connection:Be,bytes:E})),shortRefreshes:[...H].map(([Be,E])=>({connection:Be,at:E}))})}else W.t==="fail"&&(this.multiHolder.failed+=1,me(null))},ft=W=>{if(!D){if(!W)return me(null);for(let ve of W.commands)if(jr(ve,W),D)return;q=Q(q),W.next!==null&&(q=this.#h(Math.max(0,W.next-I()),()=>{q=null,Ie("tick",{},ve=>S.tick(ve))}))}};r.onDeadline=()=>D?!1:(Ie("tick",{},W=>S.tick(W)),!D&&ee===null&&(ee=this.#h(Math.max(0,r.limit+r.originReserveMs-I()),()=>{ee=null,me(null)})),!0);let St=[...f.values()].some(W=>W.refresh||W.firstByteMs===null)?null:this.peerSelection.firstByteMs(),nr=[...b].filter(([,W])=>f.get(W).rate===null).map(([W])=>W),sr={peers:d,origin:A,sharedFirstByteMs:St,sharedRate:this.peerSelection.rate(),probePeers:nr};Ie("start",this.options.traceRequests?{size:i.size,pieces:i.pieces.length,pieceSize:F,deadline:T-U,maxHolders:this.options.maxHoldersPerObject,originReserveMs:0,...r.peerOnly?{peerOnly:!0}:{},...structuredClone(sr),holders:[...b].map(([W,ve])=>[W,this.#U(ve.pubkey)])}:null,W=>S.start(W,sr),W=>{W?.late&&(this.multiHolder.late+=1),ft(W)})})}finally{v()}}#Xe(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(),h=null,u={abandoned:!1,signal:o.signal},p=()=>{u.abandoned||o.signal.aborted||(u.abandoned=!0,o.abort(ot.ABANDON_REASON))},g=null;if(i!==null){let m=c?s.deadline-r/c:-1/0;g=setTimeout(()=>{h===null&&p()},Math.max(ul,i*3,m-I()))}let f=m=>{let y=l.at(-1);if(!y)return null;let v=l[0];for(let b of l)if(b[0]<=y[0]-m)v=b;else break;return y[0]-v[0]>=150?{bytes:y[1]-v[1],ms:y[0]-v[0]}:null};return u.progress=(m,y,v)=>{let b=I();if(h===null&&(h=Number.isFinite(v)?v:b-t),l.push([b,m]),l.length>256&&l.shift(),b-ts.deadline)&&p()},u.observation=()=>{let m=l.length?l.at(-1)[0]-l[0][0]:0,y=f(Math.max(300,m/2));return{firstByteMs:h,bytes:y?.bytes??0,flowMs:y?.ms??0,totalFlowMs:m}},u.done=()=>{clearTimeout(g),e.removeEventListener("abort",a)},u}#R(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(!Zi.includes(s.outcome))return;this.#Ke(t,s);let a=p=>Number.isFinite(p)&&p>=0?p:null,l=p=>Number.isSafeInteger(p)&&p>=0?p:null,c=null,h=null;try{c=l(e?.frag?.cc)}catch{}try{h=l(e?.frag?.level)}catch{}let u={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:h,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:Fr["link-close"].includes(s.closeReason)?s.closeReason:null};this.peerRequestCounters[s.outcome]=Ve(this.peerRequestCounters[s.outcome]),this.peerRequestRecords.length===64&&(this.peerRequestRecords.shift(),this.peerRequestDropped=Ve(this.peerRequestDropped)),this.peerRequestRecords.push(u),this.#e({k:"request",load:o,at:this.#s(),range:i?[i.start,i.end]:null,...u})}catch{}}#Je(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.#Qe(i);if(this.race=l,!l)return this.inner.load(i,o,a);let c=[],h=0,u=l.sampled||t.#xe(),p={...a,onProgress:a.onProgress?(g,f,m,y)=>{try{m?.byteLength&&(u&&c.push(m.slice(0)),h+=m.byteLength)}catch{}a.onProgress(g,f,m,y)}:void 0,onSuccess:(g,f,m,y)=>{let v=qr(f),b=null,T=0;try{let B=g?.data;B?.byteLength?(u&&(b=B.slice(0)),T=B.byteLength):h&&(u&&(b=r.join(c)),T=h)}catch{b=null,T=0}l.originSucceeded=!0,a.onSuccess(g,f,m,y),t.#M(y,v),T?t.#r("origin-loaded",()=>t.#tt(l,b,T)):t.#r("origin-empty",()=>t.#z(l))},onError:(...g)=>{t.#r("origin-error",()=>t.#z(l)),a.onError(...g)},onTimeout:(...g)=>{t.#r("origin-timeout",()=>t.#z(l)),a.onTimeout(...g)}};return a.onAbort&&(p.onAbort=(...g)=>{t.#r("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,h)=>c+h.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}#Qe(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||Gi)(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.#et(o)),o}catch(t){return this.#o("begin-race",t),null}}async#et(e){if(e.keyPromise=Nt($i.encode(e.keyText)),e.key=await e.keyPromise,this.stopped)return;if(!e.sampled||!this.options.serveOnCellular&&Pt())return e.peerDone=!0,e.skipPeers=!0,this.#r("settle",()=>this.#ee(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.#r("settle",()=>this.#ee(e))}#Q(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#tt(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,Ke(this.originLatencySamples,i-e.t0),e.sampled&&(e.originDigest=await Nt(s)),e.originDone=!0,await e.keyPromise,!this.stopped&&(s&&this.#T(e.key,s),this.#r("settle",()=>this.#ee(e)))}#z(e){e.settled||e.originDone||(e.controller.abort(),e.originDone=!0,e.originFailed=!0,this.#r("settle",()=>this.#ee(e)))}async#ee(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 Nt(e.peerBytes)!==e.originDigest){this.#R(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.#R(e.peerLink,e.requestMs,e.peerBytes.byteLength),this.firstPeerSegmentAtMs===null&&(this.firstPeerSegmentAtMs=Date.now()-this.startedAt),Ke(this.peerLatencySamples,s),t.bytesFromPeers+=e.peerBytes.byteLength,s<=this.options.originFallbackMs?(t.peerInTime+=1,t.peerInTimeBytes+=e.peerBytes.byteLength):t.peerLate+=1}#T(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)}#rt(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||!Pt())}#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#nt(e,t,r=null){if(this.uploadPacer)return this.#st(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 h=xt(i.byteLength),u=r.start*h,p=Math.min(r.end*h,i.byteLength);if(!(ua)return this.#y("session-allowance"),null;let l=[...this.links.values()].filter(h=>h!==e&&(h.outboundInFlight>0||Date.now()-h.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:u}),this.lifecycle.signal,this.options.admissionTimeoutMs)===!0}catch{this.#o("upload-reservation")}if(!h||this.stopped||e.closed||this.options.serve!==!0||!this.options.serveOnCellular&&Pt())return h||(this.uploadQuotaBytes-=o),this.#y(h?"reservation-inactive":"reservation-refused"),null}if(this.counters.bytesUploaded+=o,this.counters.uploadsServed+=1,this.options.testHooks?.corruptUploads){let h=i.slice();return h[h.length>>1]^=255,h}return i}#y(e){this.counters.uploadsRefused+=1,this.uploadRefusalCounters[e]=Ve(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&&Pt()||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(!h())return null;let u=this.admissionChecks.get(e.pubkey)?.ticket??this.admitted.get(e.pubkey)?.ticket;if(this.options.admit&&!await at(()=>this.#x(e.pubkey,u,"upload"),c,this.options.admissionTimeoutMs))return this.#y("admission"),e.close("admission"),null;if(!h())return null;if(this.uploadQuotaBytes+=i.charge,o=!0,this.options.reserveUploadBytes){try{a=await at(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(!h()||this.options.admit&&this.admitted.get(e.pubkey)?.ticket!==u)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#it(){this.coreState="loading";try{let e=await Ni(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.#ot(e)}catch(e){this.coreState="failed",this.options.transferWorkerUrl!==void 0&&(this.transferWorkerState="failed",this.transferWorkerReason="core-failed"),this.#o("core",e)}}async#ot(e){this.transferWorkerState="loading";try{let t=this.options.WorkerImpl,r=await Hi({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.#L();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()}#L(){return this.options.multiHolder===!0&&this.options.mode==="peer-first"&&!!this.core&&!this.core.retired&&this.coreLinks.js===0}#at(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 ot(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,Mi(e,t)}async#lt(){let e=this.options.secretKey||Vt();if(this.pool=new _r(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 Or({pool:this.pool,swarmId:this.options.swarmId,secretKey:e,maxEventAgeSeconds:60}),this.session.onPresence(t=>this.#r("presence",()=>this.#gt(t))),this.session.onSignal(t=>this.#r("signal",()=>this.#mt(t))),this.session.onError(t=>this.#o("session",t)),this.session.start(),this.#V(),this.#k(this.options.presenceIntervalMs,.3,()=>this.#V())}#V(){if(!(!this.session||this.stopped))try{this.session.announcePresence({role:"viewer",transports:[{type:zr,publicKey:this.session.pubkey,...this.#L()?{obj:2}:{}}],have:this.#p()?[...this.held.keys()].slice(-8):[],open:this.#ht(),...this.#ne()?{ticket:this.#ne()}:{}}),this.counters.presenceSent+=1;for(let[e,t]of this.renditions){if(t{this.reannounceTimer=null,this.#V()})}#q(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.#q(t,e.rendition)||e.keys.some(r=>t.have.has(r))))}#Re(e){let t=[...this.links.values()].filter(r=>this.#q(r,e.rendition));return t.length>0&&t.every(r=>this.discovery.stale(e,r.pubkey))}#ct(e){return[...this.links.values()].filter(t=>this.#q(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()||we(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 Qi([...this.links.values()].filter(r=>!t.some(s=>!this.discovery.stale(s,r.pubkey)&&(this.#q(r,s.rendition)||s.keys.some(i=>r.have.has(i))))),{...this.options,banned:this.banned,tier:r=>this.#Ie(r)})}#F(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.#F(t))}#te(){if(this.stopped||this.options.mode!=="peer-first"||(this.#j(),!this.#re()))return;for(let i of this.discovery.contexts.values())this.discovery.rearm(i,()=>this.#ct(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.#F(s))),this.#r("discovery",()=>this.#ie(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 Qi(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}`]++}#ht(){return this.#j(),this.discovery.reserved()?!1:this.#_()||this.links.size>=2&&!!this.#Oe()}#ut(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:zr,requestId:r,payload:s}),this.counters.signalsSent+=1,!0)}catch(i){return this.counters.publishErrors+=1,this.#o("signal-send",i),!1}}#ft(e){return yl(e,this.options)}#pt(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.#te();return}if(!(this.links.has(e)||this.dials.has(e)||this.banned.has(e)||!this.#_()))return this.cooldowns.delete(e),this.#ie(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.#r("referral",()=>this.#ie(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"}#ne(){return we(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(!we(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 at(a=>{try{let l=Xi.includes(r)?r:"other";this.admissionCallCounters[l]=Ve(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,...we(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.#r("admission-refresh",async()=>{await this.#x(e,o.ticket,"refresh")&&o.open!==null&&this.#$(e,o.open)})}),this.admissionChecks.set(e,i),i.promise}async#gt({from:e,payload:t}){if(this.stopped||t.role!=="viewer")return;let r=t.transports.find(l=>l.type===zr);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.#te());let s=this.links.has(e)||this.dials.has(e),i=this.admitted.get(e);i&&we(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.#A();return}if(!s&&(this.#D(e)||!this.#_()||!this.#re())){o&&t.open!==null&&this.#$(e,t.open);return}let a=this.admissionChecks.get(e);if(s&&a){we(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.#A(),!(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.#re())return this.#ie(e)}))}#g(e,t,r,s){try{if(!Fr[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]=Ve(this.transportCounters[t][r]),this.transportRecords.length===64&&(this.transportRecords.shift(),this.transportDropped=Ve(this.transportDropped)),this.transportRecords.push(a)}catch{}}#Ne(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}}#Pe(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,Fr[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))}#se(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{}}#He(e,t,r){!r&&e.discovery&&(this.#F(e.discovery.window,!1),e.discovery=null),e.negotiation&&(e.negotiation.superseded=!0),this.#se(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}#De(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.#r("link-open",()=>this.#yt(e,t,r))},r.addEventListener("open",t.onOpen),r.readyState==="open"&&t.onOpen()}}#Ue(e,t){this.#u(e,t)&&(t.ready=!0,t.channel?.readyState==="open"&&t.onOpen())}async#ie(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.#re()){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.#Pe(!0),s=gl(),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.#He(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.#De(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 Ji(r,1200,o.controller.signal,h=>{i.negotiation===o&&!o.superseded&&this.#Ne(r,"offer",h)}),!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.#ne(),c=this.#ue(e,"offer",s,{sdp:r.localDescription.sdp,peers:this.links.size,...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.#se(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.#te()}async#mt({from:e,payload:t}){if(this.stopped||t.transport!==zr)return;let r=typeof t.payload?.sdp=="string"?t.payload.sdp:"";if(t.type==="answer"){let u=this.dials.get(e);if(!u?.outgoing||u.requestId!==t.requestId||!r)return;let p=u.negotiation;if(p.answerPending)return;if(this.#g(u.pc,"answer-received","authenticated"),!await this.#x(e,we(t.payload.ticket)?t.payload.ticket:null,"answerIncoming")){this.#u(u,p)&&this.#m(u,"failed",0,"admission");return}if(!this.#u(u,p)||!u.outgoing||u.requestId!==t.requestId||p.answerPending)return;p.answerPending=!0,this.#g(u.pc,"answer-admitted","accepted"),u.answerAt=I();try{await this.#fe(u,p,async()=>{await u.pc.setRemoteDescription({type:"answer",sdp:r}),this.#u(u,p)&&(this.#g(u.pc,"remote-installed","answer"),this.#Ue(u,p))})}catch(g){this.#u(u,p)&&(this.#o("answer",g),this.#m(u,"failed"))}return}if(t.type==="reject"){let u=this.dials.get(e);if(!u?.outgoing||u.requestId!==t.requestId)return;let p=this.#ft(t.payload);this.#m(u,"rejected",p.retryAfterMs),this.#$(e,!1),this.#pt(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,we(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.#ut(t.payload?.peers,t.payload?.requestedKey)){this.counters.offersRefused+=1,this.counters.evictionsUnavailable+=1,this.#ue(e,"reject",t.requestId,this.#dt(e));return}let u=this.#Pe(!1);a={pubkey:e,pc:u,startedAt:I(),offerSentAt:I()},this.dials.set(e,a),a.timer=this.#h(this.options.dialTimeoutMs,()=>this.#m(a,"timeout"))}let c=a.pc,h=this.#He(a,t.requestId,!1);l&&this.#g(c,"negotiation","glare-yield"),this.#g(c,"offer-admitted","accepted"),h.onDataChannel=u=>this.#De(a,h,u.channel),c.addEventListener("datachannel",h.onDataChannel);try{await this.#fe(a,h,async()=>{if(l){if(!await this.#x(e,we(t.payload.ticket)?t.payload.ticket:null,"glareBeforeRollback")){this.#u(a,h)&&this.#m(a,"failed",0,"admission");return}if(!this.#u(a,h))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,h)))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,we(t.payload.ticket)?t.payload.ticket:null,"glareAfterRollback")){this.#u(a,h)&&this.#m(a,"failed",0,"admission");return}if(!this.#u(a,h))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,h))return;this.#g(c,"remote-installed","offer");let u=await c.createAnswer();if(!this.#u(a,h)||(await c.setLocalDescription(u),!this.#u(a,h))||(await Ji(c,1200,h.controller.signal,f=>{a.negotiation===h&&!h.superseded&&this.#Ne(c,"answer",f)}),!this.#u(a,h)))return;if(!await this.#x(e,we(t.payload.ticket)?t.payload.ticket:null,"answerBeforeSend")){this.#u(a,h)&&this.#m(a,"failed",0,"admission");return}if(!this.#u(a,h))return;let p=this.#ne(),g=this.#ue(e,"answer",t.requestId,{sdp:c.localDescription.sdp,...p?{ticket:p}:{}});this.#g(c,g?"signal-send":"signal-failed","answer"),g?(this.counters.offersAccepted+=1,this.#Ue(a,h)):this.#m(a,"failed")})}catch(u){this.#u(a,h)&&(this.#o("offer",u),this.#m(a,"failed"))}}async#yt(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.#se(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.#F(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&&Ke(this.signallingSamples,I()-e.offerSentAt);let i=this.#at({pubkey:e.pubkey,pc:e.pc,channel:r,maxSegmentBytes:this.options.maxSegmentBytes,onRequest:(a,l,c)=>this.#nt(a,l,c),onHaveChange:(a,l)=>{for(let c of[...this.haveWaiters])c(l);this.#A()},onScheduleChange:()=>{for(let a of[...this.haveWaiters])a();for(let a of[...this.peerLeaseWaiters])a();this.#A()},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.#r("reannounce",()=>this.#Be()))}});this.links.set(e.pubkey,i),this.#qe(e.pubkey),this.#A(),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 pl(e.pc);this.pairTypes[o]=(this.pairTypes[o]||0)+1;for(let a of[...this.haveWaiters])a()}};var Mh=Object.freeze({version:"0.4.4",sourceCommit:"f923058503778dea2427a81330da04cce80a95c2"});export{Si as KIND_SEGMENT_COMMITMENT,ki as commitmentContent,xt as commitmentPieceSize,bl as createHlsSwarm,wr as finalizeEvent,Vt as generateSecretKey,Yt as matchFilter,Mh as relayswarmBuild,_t as segmentMediaContext,$t as verifyEvent}; +${s}${i}`,key:null,sampled:Math.random()this.#et(o)),o}catch(t){return this.#o("begin-race",t),null}}async#et(e){if(e.keyPromise=Nt($i.encode(e.keyText)),e.key=await e.keyPromise,this.stopped)return;if(!e.sampled||!this.options.serveOnCellular&&Pt())return e.peerDone=!0,e.skipPeers=!0,this.#r("settle",()=>this.#ee(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.#r("settle",()=>this.#ee(e))}#Q(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#tt(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,Ke(this.originLatencySamples,i-e.t0),e.sampled&&(e.originDigest=await Nt(s)),e.originDone=!0,await e.keyPromise,!this.stopped&&(s&&this.#T(e.key,s),this.#r("settle",()=>this.#ee(e)))}#z(e){e.settled||e.originDone||(e.controller.abort(),e.originDone=!0,e.originFailed=!0,this.#r("settle",()=>this.#ee(e)))}async#ee(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 Nt(e.peerBytes)!==e.originDigest){this.#R(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.#R(e.peerLink,e.requestMs,e.peerBytes.byteLength),this.firstPeerSegmentAtMs===null&&(this.firstPeerSegmentAtMs=Date.now()-this.startedAt),Ke(this.peerLatencySamples,s),t.bytesFromPeers+=e.peerBytes.byteLength,s<=this.options.originFallbackMs?(t.peerInTime+=1,t.peerInTimeBytes+=e.peerBytes.byteLength):t.peerLate+=1}#T(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)}#rt(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||!Pt())}#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#nt(e,t,r=null){if(this.uploadPacer)return this.#st(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 h=xt(i.byteLength),u=r.start*h,p=Math.min(r.end*h,i.byteLength);if(!(ua)return this.#y("session-allowance"),null;let l=[...this.links.values()].filter(h=>h!==e&&(h.outboundInFlight>0||Date.now()-h.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:u}),this.lifecycle.signal,this.options.admissionTimeoutMs)===!0}catch{this.#o("upload-reservation")}if(!h||this.stopped||e.closed||this.options.serve!==!0||!this.options.serveOnCellular&&Pt())return h||(this.uploadQuotaBytes-=o),this.#y(h?"reservation-inactive":"reservation-refused"),null}if(this.counters.bytesUploaded+=o,this.counters.uploadsServed+=1,this.options.testHooks?.corruptUploads){let h=i.slice();return h[h.length>>1]^=255,h}return i}#y(e){this.counters.uploadsRefused+=1,this.uploadRefusalCounters[e]=Ve(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&&Pt()||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(!h())return null;let u=this.admissionChecks.get(e.pubkey)?.ticket??this.admitted.get(e.pubkey)?.ticket;if(this.options.admit&&!await at(()=>this.#x(e.pubkey,u,"upload"),c,this.options.admissionTimeoutMs))return this.#y("admission"),e.close("admission"),null;if(!h())return null;if(this.uploadQuotaBytes+=i.charge,o=!0,this.options.reserveUploadBytes){try{a=await at(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(!h()||this.options.admit&&this.admitted.get(e.pubkey)?.ticket!==u)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#it(){this.coreState="loading";try{let e=await Ni(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.#ot(e)}catch(e){this.coreState="failed",this.options.transferWorkerUrl!==void 0&&(this.transferWorkerState="failed",this.transferWorkerReason="core-failed"),this.#o("core",e)}}async#ot(e){this.transferWorkerState="loading";try{let t=this.options.WorkerImpl,r=await Hi({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.#L();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()}#L(){return this.options.multiHolder===!0&&this.options.mode==="peer-first"&&!!this.core&&!this.core.retired&&this.coreLinks.js===0}#at(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 ot(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,Mi(e,t)}async#lt(){let e=this.options.secretKey||Vt();if(this.pool=new _r(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 Or({pool:this.pool,swarmId:this.options.swarmId,secretKey:e,maxEventAgeSeconds:60}),this.session.onPresence(t=>this.#r("presence",()=>this.#gt(t))),this.session.onSignal(t=>this.#r("signal",()=>this.#mt(t))),this.session.onError(t=>this.#o("session",t)),this.session.start(),this.#V(),this.#k(this.options.presenceIntervalMs,.3,()=>this.#V())}#V(){if(!(!this.session||this.stopped))try{this.session.announcePresence({role:"viewer",transports:[{type:zr,publicKey:this.session.pubkey,...this.#L()?{obj:2}:{}}],have:this.#p()?[...this.held.keys()].slice(-8):[],open:this.#ht(),...this.#ne()?{ticket:this.#ne()}:{}}),this.counters.presenceSent+=1;for(let[e,t]of this.renditions){if(t{this.reannounceTimer=null,this.#V()})}#q(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.#q(t,e.rendition)||e.keys.some(r=>t.have.has(r))))}#Re(e){let t=[...this.links.values()].filter(r=>this.#q(r,e.rendition));return t.length>0&&t.every(r=>this.discovery.stale(e,r.pubkey))}#ct(e){return[...this.links.values()].filter(t=>this.#q(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()||we(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 Qi([...this.links.values()].filter(r=>!t.some(s=>!this.discovery.stale(s,r.pubkey)&&(this.#q(r,s.rendition)||s.keys.some(i=>r.have.has(i))))),{...this.options,banned:this.banned,tier:r=>this.#Ie(r)})}#F(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.#F(t))}#te(){if(this.stopped||this.options.mode!=="peer-first"||(this.#j(),!this.#re()))return;for(let i of this.discovery.contexts.values())this.discovery.rearm(i,()=>this.#ct(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.#F(s))),this.#r("discovery",()=>this.#ie(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 Qi(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}`]++}#ht(){return this.#j(),this.discovery.reserved()?!1:this.#_()||this.links.size>=2&&!!this.#Oe()}#ut(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:zr,requestId:r,payload:s}),this.counters.signalsSent+=1,!0)}catch(i){return this.counters.publishErrors+=1,this.#o("signal-send",i),!1}}#ft(e){return yl(e,this.options)}#pt(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.#te();return}if(!(this.links.has(e)||this.dials.has(e)||this.banned.has(e)||!this.#_()))return this.cooldowns.delete(e),this.#ie(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.#r("referral",()=>this.#ie(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"}#ne(){return we(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(!we(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 at(a=>{try{let l=Xi.includes(r)?r:"other";this.admissionCallCounters[l]=Ve(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,...we(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.#r("admission-refresh",async()=>{await this.#x(e,o.ticket,"refresh")&&o.open!==null&&this.#$(e,o.open)})}),this.admissionChecks.set(e,i),i.promise}async#gt({from:e,payload:t}){if(this.stopped||t.role!=="viewer")return;let r=t.transports.find(l=>l.type===zr);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.#te());let s=this.links.has(e)||this.dials.has(e),i=this.admitted.get(e);i&&we(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.#A();return}if(!s&&(this.#D(e)||!this.#_()||!this.#re())){o&&t.open!==null&&this.#$(e,t.open);return}let a=this.admissionChecks.get(e);if(s&&a){we(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.#A(),!(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.#re())return this.#ie(e)}))}#g(e,t,r,s){try{if(!Fr[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]=Ve(this.transportCounters[t][r]),this.transportRecords.length===64&&(this.transportRecords.shift(),this.transportDropped=Ve(this.transportDropped)),this.transportRecords.push(a)}catch{}}#Ne(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}}#Pe(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,Fr[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))}#se(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{}}#He(e,t,r){!r&&e.discovery&&(this.#F(e.discovery.window,!1),e.discovery=null),e.negotiation&&(e.negotiation.superseded=!0),this.#se(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}#De(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.#r("link-open",()=>this.#yt(e,t,r))},r.addEventListener("open",t.onOpen),r.readyState==="open"&&t.onOpen()}}#Ue(e,t){this.#u(e,t)&&(t.ready=!0,t.channel?.readyState==="open"&&t.onOpen())}async#ie(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.#re()){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.#Pe(!0),s=gl(),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.#He(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.#De(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 Ji(r,1200,o.controller.signal,h=>{i.negotiation===o&&!o.superseded&&this.#Ne(r,"offer",h)}),!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.#ne(),c=this.#ue(e,"offer",s,{sdp:r.localDescription.sdp,peers:this.links.size,...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.#se(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.#te()}async#mt({from:e,payload:t}){if(this.stopped||t.transport!==zr)return;let r=typeof t.payload?.sdp=="string"?t.payload.sdp:"";if(t.type==="answer"){let u=this.dials.get(e);if(!u?.outgoing||u.requestId!==t.requestId||!r)return;let p=u.negotiation;if(p.answerPending)return;if(this.#g(u.pc,"answer-received","authenticated"),!await this.#x(e,we(t.payload.ticket)?t.payload.ticket:null,"answerIncoming")){this.#u(u,p)&&this.#m(u,"failed",0,"admission");return}if(!this.#u(u,p)||!u.outgoing||u.requestId!==t.requestId||p.answerPending)return;p.answerPending=!0,this.#g(u.pc,"answer-admitted","accepted"),u.answerAt=I();try{await this.#fe(u,p,async()=>{await u.pc.setRemoteDescription({type:"answer",sdp:r}),this.#u(u,p)&&(this.#g(u.pc,"remote-installed","answer"),this.#Ue(u,p))})}catch(g){this.#u(u,p)&&(this.#o("answer",g),this.#m(u,"failed"))}return}if(t.type==="reject"){let u=this.dials.get(e);if(!u?.outgoing||u.requestId!==t.requestId)return;let p=this.#ft(t.payload);this.#m(u,"rejected",p.retryAfterMs),this.#$(e,!1),this.#pt(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,we(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.#ut(t.payload?.peers,t.payload?.requestedKey)){this.counters.offersRefused+=1,this.counters.evictionsUnavailable+=1,this.#ue(e,"reject",t.requestId,this.#dt(e));return}let u=this.#Pe(!1);a={pubkey:e,pc:u,startedAt:I(),offerSentAt:I()},this.dials.set(e,a),a.timer=this.#h(this.options.dialTimeoutMs,()=>this.#m(a,"timeout"))}let c=a.pc,h=this.#He(a,t.requestId,!1);l&&this.#g(c,"negotiation","glare-yield"),this.#g(c,"offer-admitted","accepted"),h.onDataChannel=u=>this.#De(a,h,u.channel),c.addEventListener("datachannel",h.onDataChannel);try{await this.#fe(a,h,async()=>{if(l){if(!await this.#x(e,we(t.payload.ticket)?t.payload.ticket:null,"glareBeforeRollback")){this.#u(a,h)&&this.#m(a,"failed",0,"admission");return}if(!this.#u(a,h))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,h)))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,we(t.payload.ticket)?t.payload.ticket:null,"glareAfterRollback")){this.#u(a,h)&&this.#m(a,"failed",0,"admission");return}if(!this.#u(a,h))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,h))return;this.#g(c,"remote-installed","offer");let u=await c.createAnswer();if(!this.#u(a,h)||(await c.setLocalDescription(u),!this.#u(a,h))||(await Ji(c,1200,h.controller.signal,f=>{a.negotiation===h&&!h.superseded&&this.#Ne(c,"answer",f)}),!this.#u(a,h)))return;if(!await this.#x(e,we(t.payload.ticket)?t.payload.ticket:null,"answerBeforeSend")){this.#u(a,h)&&this.#m(a,"failed",0,"admission");return}if(!this.#u(a,h))return;let p=this.#ne(),g=this.#ue(e,"answer",t.requestId,{sdp:c.localDescription.sdp,...p?{ticket:p}:{}});this.#g(c,g?"signal-send":"signal-failed","answer"),g?(this.counters.offersAccepted+=1,this.#Ue(a,h)):this.#m(a,"failed")})}catch(u){this.#u(a,h)&&(this.#o("offer",u),this.#m(a,"failed"))}}async#yt(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.#se(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.#F(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&&Ke(this.signallingSamples,I()-e.offerSentAt);let i=this.#at({pubkey:e.pubkey,pc:e.pc,channel:r,maxSegmentBytes:this.options.maxSegmentBytes,onRequest:(a,l,c)=>this.#nt(a,l,c),onHaveChange:(a,l)=>{for(let c of[...this.haveWaiters])c(l);this.#A()},onScheduleChange:()=>{for(let a of[...this.haveWaiters])a();for(let a of[...this.peerLeaseWaiters])a();this.#A()},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.#r("reannounce",()=>this.#Be()))}});this.links.set(e.pubkey,i),this.#qe(e.pubkey),this.#A(),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 pl(e.pc);this.pairTypes[o]=(this.pairTypes[o]||0)+1;for(let a of[...this.haveWaiters])a()}};var Mh=Object.freeze({version:"0.4.4",sourceCommit:"b75d71bde9aa836e45b27d26d569353530a955d2"});export{Si as KIND_SEGMENT_COMMITMENT,ki as commitmentContent,xt as commitmentPieceSize,bl as createHlsSwarm,wr as finalizeEvent,Vt as generateSecretKey,Yt as matchFilter,Mh as relayswarmBuild,_t as segmentMediaContext,$t 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 0c501c3..4fb9dd8 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/f923058503778dea2427a81330da04cce80a95c2 +https://github.com/forgesworn/relayswarm/tree/b75d71bde9aa836e45b27d26d569353530a955d2 MIT License diff --git a/site/vendor/relayswarm-transfer-worker.js b/site/vendor/relayswarm-transfer-worker.js index 2820c81..f86ecfd 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 f923058503778dea2427a81330da04cce80a95c2. See media-peer-demo.NOTICE.txt. */ +/*! RelaySwarm 0.4.4 transfer worker; public source b75d71bde9aa836e45b27d26d569353530a955d2. 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};